参考博客 : 嘤桃子
一、MyBatis简介
1、MyBatis历史
??MyBatis最初是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation迁移到了Google Code。随着开发团队转投Google Code旗下, iBatis3.x正式更名MyBatis。代码于2013年11月迁移到Github。
??iBatis一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。 iBatis提供的持久层框架 包括SQL Maps和Data Access Objects(DAO)。
SQL Maps : 数据库中数据和Java数据的映射关系,MyBatis封装jdbc的过程 Data Access Objects : 使用jdbc操作数据库
2、MyBatis特性
1) MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架 高级映射:字段和实体类属性不一致的映射
2) MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集 避免:不需要手写JDBC代码,设置参数,手动获取结果集
3) MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old JavaObjects,普通的Java对象)映射成数据库中的记录 xml或注解:两种方式配置SQL,xml为主流
4) MyBatis 是一个 半自动的ORM(Object Relation Mapping)框架 半自动:需要手动编写SQL,创建表 ORM:实体对象,和数据创建映射关系
3、MyBatis下载
MyBatis下载地址:https://github.com/mybatis/mybatis-3
4、和其它持久层技术对比
- JDBC
- SQL 夹杂在Java代码中耦合度高,导致硬编码内伤
- 维护不易且实际开发需求中 SQL 有变化,频繁修改的情况多见
- 代码冗长,开发效率低
- Hibernate 和 JPA
- 操作简便,开发效率高
- 程序中的长难复杂 SQL 需要绕过框架
- 内部自动生产的 SQL,不容易做特殊优化
- 基于全映射的全自动框架,大量字段的 POJO 进行部分映射时比较困难。
- 反射操作太多,导致数据库性能下降
- MyBatis
- 轻量级,性能出色
- SQL 和 Java 编码分开,功能边界清晰。Java代码专注业务、SQL语句专注数据
- 开发效率稍逊于HIbernate,但是完全能够接受
二、搭建MyBatis
1、开发环境
IDE:idea 构建工具:maven 3.5.4 MySQL版本:MySQL 5.7 MyBatis版本:MyBatis 3.5.7
2、创建maven工程
a>打包方式:jar
b>引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
</dependencies>
3、创建MyBatis的核心配置文件
习惯上命名为mybatis-config.xml,这个文件名仅仅只是建议,并非强制要求。将来整合Spring之后,这个配置文件可以省略,所以大家操作时可以直接复制、粘贴。 核心配置文件主要用于配置连接数据库的环境以及MyBatis的全局配置信息 核心配置文件存放的位置是src/main/resources目录下
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/UserMapper.xml"/>
</mappers>
</configuration>
4、 创建mapper接口 & 实体类
MyBatis中的mapper接口相当于以前的dao。但是区别在于,mapper仅仅是接口,我们不需要 提供实现类。
- MyBatis面向接口编程的两个一致:
- 1。映射文件namespace和Mapper接口的全类名一致
- 2。映射文件中sql语句的id和mapper接口中的方法一致
public interface UserMapper {
int insertUser();
void updateUser();
void deleteUser();
User getUserById();
List<User> getAllUser();
}
User.java
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
private String gender;
private String email;
public User() {
}
public User(Integer id, String username, String password, Integer age, String gender, String email) {
this.id = id;
this.username = username;
this.password = password;
this.age = age;
this.gender = gender;
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
5、 创建MyBatis的映射文件
相关概念:ORM(Object Relationship Mapping)对象关系映射。
- 对象:Java的实体类对象
- 关系:关系型数据库
- 映射:二者之间的对应关系
1、映射文件的命名规则: 表所对应的实体类的类名+Mapper.xml 例如:表t_user,映射的实体类为User,所对应的映射文件为UserMapper.xml (一张表一个映射文件) 因此一个映射文件对应一个实体类,对应一张表的操作 MyBatis映射文件用于编写SQL,访问以及操作表中的数据 MyBatis映射文件存放的位置是src/main/resources/mappers目录下
2、MyBatis中可以面向接口操作数据,要保证两个一致:
a> mapper接口的全类名和映射文件的命名空间(namespace)保持一致 b>mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致
<?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.atguigu.mybatis.mapper.UserMapper">
<insert id="insertUser">
insert into t_user values(null, "marina", "456",23,'f',"153456@qq.com")
</insert>
<update id="updateUser">
update t_user set username = "RUOYI" where id = 4
</update>
<delete id="deleteUser">
delete from t_user where id = 5
</delete>
<select id="getUserById" resultType="com.atguigu.mybatis.pojo.User">
select * from t_user where id = 4
</select>
<select id="getAllUser" resultType="com.atguigu.mybatis.pojo.User">
select * from t_user
</select>
</mapper>
6、 通过junit测试功能
public class MyBatisTest {
@Test
public void testInsertUser() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.insertUser();
System.out.println("result: " + result);
}
@Test
public void testUpdateUser() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser();
System.out.println("updating...");
}
@Test
public void testDeleteUser() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser();
System.out.println("deleteUser-...");
}
@Test
public void testSelectUser() throws IOException {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById();
System.out.println(user);
List<User> allUser = mapper.getAllUser();
allUser.forEach(user1 -> System.out.println(user1));
}
}
7、 加入log4j日志功能
a>加入依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
b>加入log4j的配置文件
log4j的配置文件名为log4j.xml,存放的位置是src/main/resources目录下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
%m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
日志的级别 FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试) 从左到右打印的内容越来越详细
三、核心配置文件详解
<?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="jdbc.properties"></properties>
<typeAliases>
<typeAlias type="com.atguigu.mybatis.pojo.User" alias="User"></typeAlias>
<package name="com.atguigu.mybatis.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<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>
<mappers>
<package name="com.atguigu.mybatis.mapper"/>
</mappers>
</configuration>
设置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="jdbc.properties"></properties>
<typeAliases>
<package name=""></package>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<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>
<mappers>
<package name=""/>
</mappers>
</configuration>
添加模版步骤 完成后就可以直接new一个mybatis-config模版啦。 设置xxxMapper.xml配置文件模版
<?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="">
</mapper>
四、MyBatis的CRUD
- 添加
<insert id="insertUser">
insert into t_user values(null,'admin','123456',23,'男')
</insert>
- 删除
<delete id="deleteUser">
delete from t_user where id = 7
</delete>
- 修改
<update id="updateUser">
update t_user set username='ybc',password='123' where id = 6
</update>
- 查询
<select id="getUserById" resultType="com.atguigu.mybatis.bean.User">
select * from t_user where id = 2
</select>
注意: 1、查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射 关系 resultType:自动映射,用于属性名和表中字段名一致的情况 resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况 2、当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常 TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值
工具类
package com.atguigu.mybatis.utils;
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.InputStream;
public class SqlSessionUtils {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
五、获取参数值的两种方式(重点)
??MyBatis获取参数值的两种方式:${}和#{}
??${}的本质就是字符串拼接,#{}的本质就是占位符赋值
??${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引 号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自 动添加单引号
JDBC方式中的占位符和字符串拼接
@Test
public void testJDBC() throws SQLException, ClassNotFoundException {
String username = "cherry";
Class.forName("");
Connection connection = DriverManager.getConnection("", "", "");
PreparedStatement preparedStatement = connection.prepareStatement("select * from t_user where username = '" + username + "'");
PreparedStatement ps2 = connection.prepareStatement("select * from t_user where username = ?");
ps2.setString(1, username);
}
1、单个字面量类型
若mapper接口中的方法参数为单个的字面量类型 此时可以使用${} 和#{} 以任意的名称获取参数的值,注意${} 需要手动加单引号
public interface ParameterMapper {
User getUserByUserName(String username);
}
#{}
<select id="getUserByUserName" resultType="User">
select * from t_user where username = #{username}
</select>
${}
<select id="getUserByUserName" resultType="User">
select * from t_user where username = '${username}'
</select>
测试类
@Test
public void testgetUserByUserName(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.getUserByUserName("RUOYI");
System.out.println(user);
}
2、多个字面量类型(**)
若mapper接口中的方法参数为多个时
此时MyBatis会自动将这些参数放在一个map集合中 ,以arg0,arg1…为键,以参数为值;以param1,param2…为键,以参数为值;因此只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值,注意${} 需要手动加单引号
public interface ParameterMapper {
User checkLogin(String username, String password);
}
<select id="checkLogin" resultType="User">
select * from t_user where username = #{arg0} and password = #{arg1}
select * from t_user where username = '#{param1}' and password = '#{param2}'
</select>
测试类
@Test
public void testCheckLogin(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLogin("RUOYI","123456");
System.out.println(user);
}
3、map集合类型(**)
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中 只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值,注意${} 需要手动加单引号
public interface ParameterMapper {
User checkLoginByMap(Map<String, Object> map);
}
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
测试类
@Test
public void testCheckLoginByMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("username","RUOYI");
map.put("password","123456");
User user = mapper.checkLoginByMap(map);
System.out.println(user);
}
4、 实体类类型(**)
若mapper接口中的方法参数为实体类对象时
此时可以使用${} 和#{} ,通过访问实体类对象中的属性名获取属性值,注意${}需要手动加单引号
public interface ParameterMapper {
int insertUser(User user);
}
<insert id="insertUser">
insert into t_user values(null, #{username}, #{password}, #{age}, #{gender}, #{email})
</insert>
测试类
@Test
public void testInsertUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = new User(null, "Pandora", "4444", 66, "m", "1111@gmail.com");
mapper.insertUser(user);
}
5、使用@Param标识参数(**)
可以通过@Param注解标识mapper接口中的方法参数
此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值;以 param1,param2…为键,以参数为值;只需要通过${} 和#{} 访问map集合的键就可以获取相对应的值, 注意${} 需要手动加单引号
public interface ParameterMapper {
User checkLoginByParam(@Param("username") String username, @Param("password") String password);
}
<select id="checkLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
测试类
@Test
public void testCheckLoginByParam(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = mapper.checkLoginByParam("RUOYI","123456");
System.out.println(user);
}
6、数组和集合(动态SQL中讲解)
六、MyBatis的各种查询功能
public interface SelectMapper {
User getUserById(@Param("id") Integer id);
List<User> getAllUser();
Integer getCount();
Map<String, Object> getUserByIdToMap(Integer id);
@MapKey("id")
Map<String, Object> getAllUserToMap();
}
1、查询一个实体类对象
public interface SelectMapper {
User getUserById(@Param("id") Integer id);
}
<select id="getUserById" resultType="User">
select * from t_user where id = #{id}
</select>
测试类
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
User userById = mapper.getUserById(4);
System.out.println(userById);
}
2、查询一个List集合
public interface SelectMapper {
List<User> getAllUser();
}
<select id="getAllUser" resultType="User">
select * from t_user
</select>
测试类
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
List<User> allUser = mapper.getAllUser();
allUser.forEach(user -> System.out.println(user));
}
3、查询单个数据
public interface SelectMapper {
Integer getCount();
}
<select id="getCount" resultType="java.lang.Integer">
select count(*) from t_user
</select>
测试类
@Test
public void testGetCount(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getCount());
}
默认类型别名
4、 查询一条数据为map集合
public interface SelectMapper {
Map<String, Object> getUserByIdToMap(Integer id);
}
<select id="getUserByIdToMap" resultType="map">
select * from t_user where id = #{id}
</select>
测试类
@Test
public void testgetUserByIdToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
System.out.println(mapper.getUserByIdToMap(4));
}
5、查询多条数据为map集合
方式一
List<Map<String, Object>> getAllUserToMap();
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
方式二
public interface SelectMapper {
@MapKey("id")
Map<String, Object> getAllUserToMap();
}
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
结果:
七、特殊SQL的执行
1、模糊查询
模糊查询中使用 #{} 可能会出现一些问题,所以使用 ${}
public interface SQLMapper {
List<User> getUserByLike(@Param("username") String username);
}
<select id="getUserByLike" resultType="User">
select * from t_user where username like "%"#{username}"%"
</select>
测试类
@Test
public void testGetUserByLike(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> user = mapper.getUserByLike("RUOYI");
System.out.println(user);
}
2、批量删除
public interface SQLMapper {
int deleteMore(@Param("ids") String ids);
}
<delete id="deleteMore">
delete from t_user where id in (${ids})
</delete>
测试类
@Test
public void testDeleteMore(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
int result = mapper.deleteMore("12, 13");
System.out.println(result);
}
3、动态设置表名
public interface SQLMapper {
List<User> getUserByTableName(String tableName);
}
<select id="getUserByTableName" resultType="User">
select * from ${tableName}
</select>
测试类
@Test
public void testGetUserByTableName(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
List<User> t_user = mapper.getUserByTableName("t_user");
System.out.println(t_user);
}
4、添加功能获取自增的主键
public interface SQLMapper {
void insetUser(User user);
}
<insert id="insetUser" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(null, #{username}, #{password},#{age},#{gender},#{email})
</insert>
测试类
@Test
public void testInsetUser(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SQLMapper mapper = sqlSession.getMapper(SQLMapper.class);
mapper.insetUser(new User(null, "兔兔","111",11,"f","abc@qq.com"));
}
八、自定义映射resultMap
package com.atguigu.mybatis.pojo;
public class Dept {
private Integer did;
private String deptName;
@Override
public String toString() {
return "Dept{" +
"did=" + did +
", deptName='" + deptName + '\'' +
'}';
}
getset...
}
package com.atguigu.mybatis.pojo;
public class Emp {
private Integer eid;
private String empName;
private Integer age;
private String sex;
private String email;
private Dept dept;
public Emp() {
}
public Emp(Integer eid, String empName, Integer age, String sex, String email) {
this.eid = eid;
this.empName = empName;
this.age = age;
this.sex = sex;
this.email = email;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", empName='" + empName + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
getset...
}
1、resultMap处理字段和属性的映射关系
(1)实用resultMap映射
若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射
<resultMap id="userMap" type="User">
<id property="id" column="id"></id>
<result property="userName" column="user_name"></result>
<result property="password" column="password"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</resultMap>
<select id="testMohu" resultMap="userMap">
select id,user_name,password,age,sex from t_user where user_name like concat('%',#{mohu},'%')
</select>
(2)实用全局配置
若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性 名符合Java的规则(使用驼峰)
此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系 ??a>可以通过为字段起别名的方式,保证和实体类中的属性名保持一致 ??b>可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可以在查询表中数据时,自动将_类型的字段名转换为驼峰
例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为 userName
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
(3)查询SQL起别名
<select id="testMohu" resultMap="userMap">
select id,user_name as 'userName',password,age,sex from t_user where user_name like concat('%',#{mohu},'%')
</select>
2、多对一映射处理
查询员工信息以及员工所对应的部门信息
public interface EmpMapper {
Emp getEmpAndDept(@Param("eid") Integer eid);
}
a>级联方式处理映射关系
<resultMap id="empDeptMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<result column="did" property="dept.did"></result>
<result column="dname" property="dept.dname"></result>
</resultMap>
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
select emp.*,dept.* from t_emp emp
left join t_dept dept on emp.did = dept.did
where emp.eid = #{eid}
</select>
b>使用association处理映射关系
<resultMap id="empDeptMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<association property="dept" javaType="Dept">
<id column="did" property="did"></id>
<result column="dname" property="dname"></result>
</association>
</resultMap>
<select id="getEmpAndDeptByEid" resultMap="empDeptMap">
select emp.*,dept.* from t_emp emp
left join t_dept dept on emp.did = dept.did
where emp.eid = #{eid}
</select>
c>分步查询
1)查询员工信息
Emp getEmpByStep(@Param("eid") int eid);
<resultMap id="empDeptStepMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<association property="dept"
select="com.atguigu.MyBatis.mapper.DeptMapper.getEmpDeptByStep"
column="did">
</association>
</resultMap>
<select id="getEmpByStep" resultMap="empDeptStepMap">
select * from t_emp where eid = #{eid}
</select>
2)根据员工所对应的部门id查询部门信息
Dept getEmpDeptByStep(@Param("did") int did);
<select id="getEmpDeptByStep" resultType="Dept">
select * from t_dept where did = #{did}
</select>
延迟加载
分步查询的优点: ??可以实现延迟加载,但是必须在核心配置文件中设置全局配置信息:
- lazyLoadingEnabled:延迟加载的全局开关。当开启时,所有关联对象都会延迟加载
- aggressiveLazyLoading:当开启时,任何方法的调用都会加载该对象的所有属性。 否则,每个
属性会按需加载
??此时就可以实现按需加载,获取的数据是什么,就只会执行相应的sql。此时可通过association和 collection中的fetchType属性设置当前的分步查询是否使用延迟加载,fetchType="lazy(延迟加载)|eager(立即加载)"
通过fetchType参数,可以手动控制延迟加载或立即加载,否则根据全局配置的属性决定是延迟加载还是立即加载。
<resultMap id="empDeptStepMap" type="Emp">
<id column="eid" property="eid"></id>
<result column="ename" property="ename"></result>
<result column="age" property="age"></result>
<result column="sex" property="sex"></result>
<association property="dept"
select="com.atguigu.MyBatis.mapper.DeptMapper.getEmpDeptByStep"
column="did"
fetchType="eager">
</association>
</resultMap>
<select id="getEmpByStep" resultMap="empDeptStepMap">
select * from t_emp where eid = #{eid}
</select>
3、一对多映射处理
根据部门id查找部门以及部门中的员工信息
?? 需要查询一对多、多对一的关系,需要在“一”的pojo中加入List<多>属性,在“多”的pojo中加入“一”。 ?? 也就是说,在Dept类中,要加入private List emps;;在Emp类中,要加入private Dept dept;。然后给他们各自添加get、set方法,重写构造器和toString()
a>collection处理映射
/**
* 根据部门id查新部门以及部门中的员工信息
* @param did
* @return
*/
Dept getDeptEmpByDid(@Param("did") int did);
<resultMap id="deptEmpMap" type="Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
<collection property="emps" ofType="Emp">
<id property="eid" column="eid"></id>
<result property="ename" column="ename"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</collection>
</resultMap>
<select id="getDeptEmpByDid" resultMap="deptEmpMap">
select dept.*,emp.* from t_dept dept
left join t_emp emp on dept.did = emp.did
where dept.did = #{did}
</select>
b>分步查询
1)查询部门信息
Dept getDeptByStep(@Param("did") int did);
<resultMap id="deptEmpStep" type="Dept">
<id property="did" column="did"></id>
<result property="dname" column="dname"></result>
<collection property="emps"
fetchType="eager"
select="com.atguigu.MyBatis.mapper.EmpMapper.getEmpListByDid"
column="did"> </collection>
</resultMap>
<select id="getDeptByStep" resultMap="deptEmpStep">
select * from t_dept where did = #{did}
</select>
2)根据部门id查询部门中的所有员工
List<Emp> getEmpListByDid(@Param("did") int did);
<select id="getEmpListByDid" resultType="Emp">
select * from t_emp where did = #{did}
</select>
九、动态SQL()
??Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题。
1、if
if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
应用场景:多条件查询
public interface DynamicSQLMapper {
List<Emp> getEmpByCondition(Emp emp);
}
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</select>
测试类
@Test
public void testGetEmpByCondition(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
List<Emp> emp1 = mapper.getEmpByCondition(new Emp(null, "Apple", 22, "女", "123@gmail.com"));
List<Emp> emp2 = mapper.getEmpByCondition(new Emp(null, "Apple", null, "女", "123@gmail.com"));
List<Emp> emp3 = mapper.getEmpByCondition(new Emp(null, null, null, "女", "123@gmail.com")); System.out.println(emp1);
System.out.println(emp1);
System.out.println(emp2);
System.out.println(emp3);
}
2、where、set
应用场景:多条件查询
public interface DynamicSQLMapper {
List<Emp> getEmpByCondition(Emp emp);
}
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
</where>
</select>
测试类
@Test
public void testGetEmpByCondition2(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
List<Emp> emp1 = mapper.getEmpByCondition(new Emp(null, "Apple", 22, "女", "123@gmail.com"));
List<Emp> emp2 = mapper.getEmpByCondition(new Emp(null, "Apple", null, "女", "123@gmail.com"));
List<Emp> emp3 = mapper.getEmpByCondition(new Emp(null, null, null, "女", "123@gmail.com")); System.out.println(emp1);
System.out.println(emp1);
System.out.println(emp2);
System.out.println(emp3);
}
where和if一般结合使用: a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字 b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的 and去掉 注意:where标签不能去掉条件最后多余的and
3、trim
多条件查询
public interface DynamicSQLMapper {
List<Emp> getEmpByCondition(Emp emp);
}
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age} or
</if>
<if test="email != null and email != ''">
email = #{email} and
</if>
<if test="sex != null and sex != ''">
sex = #{sex}
</if>
</trim>
</select>
测试类
@Test
public void testGetEmpByCondition3(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
List<Emp> emp1 = mapper.getEmpByCondition(new Emp(null, "Apple", 22, "女", "123@gmail.com"));
List<Emp> emp2 = mapper.getEmpByCondition(new Emp(null, "Apple", null, "女", "123@gmail.com"));
List<Emp> emp3 = mapper.getEmpByCondition(new Emp(null, null, null, "女", "123@gmail.com"));
System.out.println(emp1);
System.out.println(emp2);
System.out.println(emp3);
}
4、choose、when、otherwise
choose、when、otherwise相当于if…else if…else
public interface DynamicSQLMapper {
List<Emp> getEmpByChoose(Emp emp);
}
<select id="getEmpByChoose" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName != null and empName != ''">
emp_name = #{empName}
</when>
<when test="age != null and age != ''">
age = #{age}
</when>
<when test="sex != null and sex != ''">
sex = #{sex}
</when>
<when test="email != null and email != ''">
email = #{email}
</when>
<otherwise>
did = 2
</otherwise>
</choose>
</where>
</select>
测试类
@Test
public void testGetEmpByChoose(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
List<Emp> emp1 = mapper.getEmpByChoose(new Emp(null, "Apple", 22, "女", "123@gmail.com"));
List<Emp> emp2 = mapper.getEmpByChoose(new Emp(null, "Apple", null, "女", "123@gmail.com"));
List<Emp> emp3 = mapper.getEmpByChoose(new Emp(null, null, null, "", ""));
System.out.println(emp1);
System.out.println(emp2);
System.out.println(emp3);
}
5、foreach
应用场景1: 通过数组实现批量删除
public interface DynamicSQLMapper {
int deleteMoreByArray(@Param("eids") Integer[] eids);
}
<delete id="deleteMoreByArray">
delete from t_emp where eid in
<foreach collection="eids" item="eid" separator="," open="(" close=")">
#{eid}
</foreach>
</delete>
<delete id="deleteMoreByArray">
delete from t_emp where
<foreach collection="eids" item="eid" separator="or">
eid = #{eid}
</foreach>
</delete>
测试类
@Test
public void testDeleteMoreByArray(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
int result = mapper.deleteMoreByArray(new Integer[]{7, 8, 9});
System.out.println(result);
}
应用场景2: 通过list集合实现批量添加
public interface DynamicSQLMapper {
int insertMoreByList(@Param("emps") List<Emp> emps);
}
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null, #{emp.empName}, #{emp.age}, #{emp.sex}, #{emp.email}, null)
</foreach>
</insert>
测试类
@Test
public void testInsertMoreByList(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
Emp emp1 = new Emp(null, "Mary", 23, "女", "11111@qq.com");
Emp emp2 = new Emp(null, "Linda", 23, "女", "1144111@qq.com");
Emp emp3 = new Emp(null, "Jackoline", 23, "女", "1122111@qq.com");
List<Emp> emps = Arrays.asList(emp1, emp2, emp3);
System.out.println(mapper.insertMoreByList(emps));
}
6、sql片段
public interface DynamicSQLMapper {
List<Emp> getAllEmpNameAndAge();
}
<sql id="empColumns">emp_name, age</sql>
<select id="getAllEmpNameAndAge" resultType="Emp">
select <include refid="empColumns"></include> from t_emp
</select>
测试类
@Test
public void testGetAllEmp(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
System.out.println(mapper.getAllEmpNameAndAge());
}
十、MyBatis的缓存
一级缓存和二级缓存级别不一样,一级缓存默认开启. 缓存只对查询功能有效
1、一级缓存
一级缓存是SqlSession级别的,通过同一个SqlSession查询的数据会被缓存,下次查询相同的数据,就 会从缓存中直接获取,不会从数据库重新访问
使一级缓存失效的四种情况:
- 不同的SqlSession对应不同的一级缓存
- 同一个SqlSession但是查询条件不同
- 同一个SqlSession两次查询期间执行了任何一次增删改操作
- 同一个SqlSession两次查询期间手动清空了缓存
(1) 不同的SqlSession对应不同的一级缓存
@Test
public void testCache(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
Emp emp1 = mapper.getEmpById(3);
System.out.println(emp1);
System.out.println("========第二次调用========从缓存中取数据");
Emp emp2 = mapper.getEmpById(3);
System.out.println(emp2);
System.out.println("\n========即使用的不是同一个Mapper,也同样从缓存中取(同一个sqlsession)========");
CacheMapper mapper2 = sqlSession.getMapper(CacheMapper.class);
Emp empByMapper2 = mapper2.getEmpById(3);
System.out.println(empByMapper2);
System.out.println("\n========一级缓存的范围在sqlsession中,换一个新的sqlsession就会再次用sql读取数据========");
SqlSession sqlSession2 = SqlSessionUtils.getSqlSession();
CacheMapper mapper2BySqlSession2 = sqlSession2.getMapper(CacheMapper.class);
System.out.println(mapper2BySqlSession2.getEmpById(3));
}
(2)同一个SqlSession但是查询条件不同
@Test
public void testCache3(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
System.out.println("=====第一次获取数据=====");
Emp emp1 = mapper.getEmpById(3);
System.out.println(emp1);
System.out.println("\n=====查询条件不同=====");
Emp emp2 = mapper.getEmpById(5);
System.out.println(emp2);
}
(3) 同一个SqlSession两次查询期间执行了任何一次增删改操作
@Test
public void testCache2(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
System.out.println("=====第一次获取数据=====");
Emp emp1 = mapper.getEmpById(3);
System.out.println(emp1);
Emp emp2 = mapper.getEmpById(3);
System.out.println(emp2);
System.out.println("\n=====进行增删改操作=====");
mapper.insetEmp(new Emp(null, "Joey", 44, "男", "8888@gmai.com"));
System.out.println("\n=====同一个sqlsession,再获取数据=====");
Emp emp3 = mapper.getEmpById(3);
System.out.println(emp3);
}
(4)同一个SqlSession两次查询期间手动清空了(一级)缓存
@Test
public void testCache4(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
CacheMapper mapper = sqlSession.getMapper(CacheMapper.class);
System.out.println("=====第一次获取数据=====");
Emp emp1 = mapper.getEmpById(3);
System.out.println(emp1);
System.out.println("\n=====两次查询期间手动清空缓存=====");
sqlSession.clearCache();
System.out.println("\n=====再次查询id=3的emp=====");
Emp emp2 = mapper.getEmpById(3);
System.out.println(emp2);
}
2、二级缓存
二级缓存是SqlSessionFactory 级别,通过同一个SqlSessionFactory 创建的SqlSession 查询的结果会被缓存;此后若再次执行相同的查询语句,结果就会从缓存中获取
二级缓存开启的条件
- 在核心配置文件中,设置全局配置属性
cacheEnabled=“true" ,默认为true ,不需要设置 - 在映射文件中设置标签
<cache /> - 二级缓存必须在
SqlSession关闭或提交 之后有效 - 查询的数据所转换的实体类类型必须
实现序列化的接口
?? 使二级缓存失效的情况: 两次查询之间执行了任意的增删改,会使一级和二级缓存同时失效 没有提交sqlsession时,数据会保存在一级缓存中,提交后,会保存在二级缓存中。
在映射文件中设置标签<cache />
测试
@Test
public void testCacheTwo(){
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
CacheMapper mapper1 = sqlSession1.getMapper(CacheMapper.class);
System.out.println(mapper1.getEmpById(1));
System.out.println("Cache Hit Ratio:缓存命中率,指的是在缓存中有没有这条数据");
System.out.println("=====二级缓存未打开,没从缓存中获取数据=====");
SqlSession sqlSession2 = sqlSessionFactory.openSession(true);
CacheMapper mapper2 = sqlSession2.getMapper(CacheMapper.class);
System.out.println(mapper2.getEmpById(1));
} catch (IOException e) {
e.printStackTrace();
}
}
关闭sqlSession,再看是用sql从数据库读取数据还是从缓存中取数据:
3、二级缓存相关配置
在mapper配置文件中添加的cache标签可以设置一些属性:
-
eviction属性:缓存回收策略
- LRU(Least Recently Used) –
最近最少使用 的:移除最长时间不被使用的对象。 - FIFO(First in First out) –
先进先出 :按对象进入缓存的顺序来移除它们。 - SOFT –
软引用 :移除基于垃圾回收器状态和软引用规则的对象。 - WEAK –
弱引用 :更积极地移除基于垃圾收集器状态和弱引用规则的对象。 默认的是 LRU。 -
flushInterval属性:刷新间隔,单位毫秒 默认情况是不设置 ,也就是没有刷新间隔,缓存仅仅调用语句(增删改) 时刷新 -
size属性:引用数目,正整数 代表缓存最多可以存储多少个对象 ,太大容易导致内存溢出 -
readOnly属性:只读,true/false
true:只读缓存; 会给所有调用者返回缓存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。【性能好】false:读写缓存; 会返回缓存对象的拷贝(通过序列化)。这会慢一些,但是安全,因此默认是 false。【安全】
4、缓存查询顺序
- 先查询二级缓存,因为二级缓存中可能会有其他程序已经查出来的数据,可以拿来直接使用。
- 如果二级缓存没有命中,再查询一级缓存
- 如果一级缓存也没有命中,则查询数据库
- SqlSession关闭之后,一级缓存中的数据会写入二级缓存。
5、整合第三方缓存EHCache
只能代替二级缓存! ?? 这部分只要会配置就可以了。
(1)添加依赖
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="这里改成你需要保存缓存的磁盘路径"/>
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
(3)设置二级缓存类型
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
(4)加入logback日志 存在SLF4J时,作为简易日志的log4j将失效,此时我们需要借助SLF4J的具体实现logback来打印日志。 创建logback的配置文件logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT">
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.atguigu.mybatis.mapper" level="DEBUG"/>
</configuration>
十一、MyBatis逆向工程
示例:t_dept和t_emp
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyBatis_MBG</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
在src/main/resources下创建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="jdbc.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<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>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=写你的数据库密码
创建log4j.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jakarta.apache.org/log4j/ ">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
%m (%F:%L) \n"/>
</layout>
</appender>
<logger name="java.sql">
<level value="debug"/>
</logger>
<logger name="org.apache.ibatis">
<level value="info"/>
</logger>
<root>
<level value="debug"/>
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
(3)创建逆向工程的配置文件 文件名必须是:generatorConfig.xml ?? “http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"这条报红不用管。 ?? 注意:mac环境下,\要修改为/,windows才是targetProject=”./src/main/java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="这里改成你自己的数据库密码">
</jdbcConnection>
<javaModelGenerator targetPackage="com.atguigu.mybatis.pojo"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.atguigu.mybatis.mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>
(4)执行MBG插件的generate目标
MyBatis3Simple
MyBatis3Simmple只有5个方法
public interface EmpMapper {
int deleteByPrimaryKey(Integer eid);
int insert(Emp record);
Emp selectByPrimaryKey(Integer eid);
List<Emp> selectAll();
int updateByPrimaryKey(Emp record);
}
<?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.atguigu.mybatis.mapper.EmpMapper" >
<resultMap id="BaseResultMap" type="com.atguigu.mybatis.pojo.Emp" >
<id column="eid" property="eid" jdbcType="INTEGER" />
<result column="emp_name" property="empName" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="sex" property="sex" jdbcType="CHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="did" property="did" jdbcType="INTEGER" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_emp
where eid = #{eid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.atguigu.mybatis.pojo.Emp" >
insert into t_emp (eid, emp_name, age,
sex, email, did)
values (#{eid,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
#{sex,jdbcType=CHAR}, #{email,jdbcType=VARCHAR}, #{did,jdbcType=INTEGER})
</insert>
<update id="updateByPrimaryKey" parameterType="com.atguigu.mybatis.pojo.Emp" >
update t_emp
set emp_name = #{empName,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
sex = #{sex,jdbcType=CHAR},
email = #{email,jdbcType=VARCHAR},
did = #{did,jdbcType=INTEGER}
where eid = #{eid,jdbcType=INTEGER}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select eid, emp_name, age, sex, email, did
from t_emp
where eid = #{eid,jdbcType=INTEGER}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
select eid, emp_name, age, sex, email, did
from t_emp
</select>
</mapper>
MyBatis3
public interface EmpMapper {
int countByExample(EmpExample example);
int deleteByExample(EmpExample example);
int deleteByPrimaryKey(Integer eid);
int insert(Emp record);
int insertSelective(Emp record);
List<Emp> selectByExample(EmpExample example);
Emp selectByPrimaryKey(Integer eid);
int updateByExampleSelective(@Param("record") Emp record, @Param("example") EmpExample example);
int updateByExample(@Param("record") Emp record, @Param("example") EmpExample example);
int updateByPrimaryKeySelective(Emp record);
int updateByPrimaryKey(Emp record);
}
package com.atguigu.mybatis.test;
import com.atguigu.mybatis.mapper.EmpMapper;
import com.atguigu.mybatis.pojo.Emp;
import com.atguigu.mybatis.pojo.EmpExample;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MBGTest {
@Test
public void testMBG(){
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
mapper.updateByPrimaryKeySelective(new Emp(1,"admin",22,null,"456@qq.com",3));
} catch (IOException e) {
e.printStackTrace();
}
}
}
十二、分页插件
1、分页插件的使用步骤
(1)添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
(2)核心配置文件中配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
2、使用
@Test
public void test2(){
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
System.out.println("\n查询功能前开启分页");
PageHelper.startPage(2, 4);
List<Emp> emps = mapper.selectByExample(null);
emps.forEach(emp -> System.out.println(emp));
System.out.println("\n");
PageInfo<Emp> pages = new PageInfo<>(emps, 5);
System.out.println("PageInfo----->"+pages);
} catch (IOException e) {
e.printStackTrace();
}
}
PageInfo{undefined
pageNum=8, pageSize=4, size=2, startRow=29, endRow=30, total=30, pages=8,
list=Page{count=true, pageNum=8, pageSize=4, startRow=28, endRow=32, total=30, pages=8, reasonable=false, pageSizeZero=false},
prePage=7, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true, hasNextPage=false, navigatePages=5, navigateFirstPage4, navigateLastPage8, navigatepageNums=[4, 5, 6, 7, 8]
}
常用数据:
pageNum:当前页的页码
pageSize:每页显示的条数
size:当前页显示的真实条数
total:总记录数
pages:总页数
prePage:上一页的页码
nextPage:下一页的页码
isFirstPage/isLastPage:是否为第一页/最后一页
hasPreviousPage/hasNextPage:是否存在上一页/下一页
navigatePages:导航分页的页码数
navigatepageNums:导航分页的页码,[1,2,3,4,5]
|