(二)Mybatis总结之通过Dao层与数据交互
Mybatis概述
定义: Mybatis是一个支持普通sql查询,存储过程和高级映射的优秀持久层框架。
- Mybatis是(半自动的)跟数据库打交道的orm(object relationship mapping 对象 关系 映射)框架.
- MyBatis 是一个优秀的基于 Java 的持久层框架,它内部封装了 JDBC(Java数据库连接),使开发者只需关注 SQL 语句本身,而不用再花费精力去处理诸如注册驱动、创建 Connection、配置 Statement 等繁杂过程。
对框架的粗浅理解
框架作用:解耦,即降低耦合度,减少开发时间(偷懒)的东西,但是并不代表框架的运行速度很高。以下两个原则是框架的重要思想。
重构原则:事不过三,三则重构(有三个地方代码重复)
- “高内聚低耦合”做法:
- 写且只写一次
- 一个类只做一种事
- 一个方法只做一件事
Mybatis的特点
- Sql语句写在XML文件中,实现了代码与Sql分离,降低耦合度
- 半自动的mybatis更利于开发人员设计Sql语句
- 简单易学
- 支持动态Sql
Mybatis配置和初步使用
Mybatis通过dao层与数据交互
1.pom.xml导入相应依赖
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
Maven要按照大佬博客说的配置,接下来file-->settings-->Maven-->Maven home directory设置为
Maven安装包路径
然后user settings file 设置为安装包路径
\conf\settings.xml,否则导依赖失败
2.mybatis核心配置mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="mysql.properties"/>
<settings>
<!--全局性设置懒加载。如果设为‘false’,则所有相关联的都会被初始化加载,默认值为false-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。默认值为true-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<typeAliases>
<!-- 其实就是将bean的替换成一个短的名字-->
<typeAlias type="com.qf.pojo.User" alias="User"/>
</typeAliases>
<!--对事务的管理和连接池的配置-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED"><!--POOLED:使用Mybatis自带的数据库连接池来管理数据库连接-->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--mapping文件路径配置-->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.配置mysql.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/demo1?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
jdbc.username=root
jdbc.password=123456
其中?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
是为了防止乱码而加的
4.配置映射文件,以下有增删改查sql语句
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qf.mybatisdemo.pojo.User">
<!--部分查询->
<select id="getUserByName" resultType="com.qf.mybatisdemo.pojo.User" parameterType="java.lang.String">
SELECT * FROM USER where username = #{username}
</select>
<insert id="addUser" parameterType="com.qf.mybatisdemo.pojo.User" >
insert into USER(username,age) values(#{username},#{age})
</insert>
<update id="updateUserAge" parameterType="com.qf.mybatisdemo.pojo.User">
update user set age=#{age} where username=#{username}
</update>
<delete id="deleUser" parameterType="com.qf.mybatisdemo.pojo.User">
delete from user where username=#{username} and age=#{age}
</delete>
</mapper>
5.创建与数据库表的字段对应的实体类
package com.qf.mybatisdemo.pojo;
public class User {
String username;
int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
6.创建会话(dao层与数据库交互数据的介质)接口
package com.qf.mybatisdemo.dao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class BaseDao {
public SqlSession getSqlSession() {
String fileName = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(fileName);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
7.增删改查接口
package com.qf.mybatisdemo.dao;
import com.qf.mybatisdemo.pojo.User;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class UserDao extends BaseDao{
User user;
/**
* 根据名字查询
*/
public User getUserByName(String userName) {
SqlSession sqlSession = this.getSqlSession();
user = sqlSession.selectOne("getUserByName",userName);
return user;
}
/**
* 增
*/
public int addUser(User user) {
int count = 0;
SqlSession sqlSession = this.getSqlSession();
count = sqlSession.insert("addUser",user);
sqlSession.commit();
return count;
}
/**
* 改
*/
public int updateUserAge(User user) {
int count= 0;
SqlSession sqlSession = this.getSqlSession();
count = sqlSession.update("updateUserAge",user);
sqlSession.commit();
return count;
}
/**
* 删除
*/
public int deleUser(User user) {
int count= 0;
SqlSession sqlSession = this.getSqlSession();
count = sqlSession.update("deleUser",user);
sqlSession.commit();
return count;
}
}
8.测试类
package com.qf.mybatisdemo;
import com.qf.mybatisdemo.dao.UserDao;
import com.qf.mybatisdemo.pojo.User;
import org.junit.Test;
import javax.jws.soap.SOAPBinding;
public class TestMybatis {
UserDao userDao;
/**
* 根据名字查询
*/
@Test
public void getUserByName () {
User user;
user = userDao.getUserByName("张三");
System.out.println(user);
}
public static void main(String[] args) {
UserDao userDao = new UserDao();
/**
* 增
*/
// User user = new User();
// int count = 0;
// user.setAge(18);
// user.setUsername("小风");
// count = userDao.addUser(user);
// System.out.println(count);
/**
* 改
*/
// User user = new User();
// int count = 0;
// user.setAge(20);
// user.setUsername("小风");
// count = userDao.updateUserAge(user);
// System.out.println("新的"+count);
/**
* 删
*/
User user = new User();
int count = 0;
user.setAge(20);
user.setUsername("小风");
count = userDao.deleUser(user);
System.out.println(count);
}
}