MyBatis
MyBatis环境搭建
我这个是使用IDEA,基于Maven搭建的
- 首先建立一个空的Maven项目或者模块
- 在pom.xml中引入所需依赖
<?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">
<parent>
<artifactId>ssm</artifactId>
<groupId>com.itzhh.ssm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>mybatis</artifactId>
<dependencies>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
- 在resources下面创建核心配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 顺序
properties?,settings?,typeAliases?,typeHandlers?,
objectFactory?,objectWrapperFactory?,reflectorFactory?,
plugins?,environments?,databaseIdProvider?,mappers?)".
-->
<!--引入properties文件-->
<properties resource="jdbc.properties"/>
<settings>
<!-- 将下划线映射为驼峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 设置类型别名-->
<typeAliases>
<!-- <typeAlias type="com.itzhh.mybatisOne.Entity.User" alias="abc"/>-->
<!-- <typeAlias type="com.itzhh.mybatisOne.Entity.User" />-->
<!-- 默认别名:类名,不区分大小写-->
<!-- 通过包名指定别名,此包下所有类都有别名-->
<package name="com.itzhh.mybatisOne.Entity"/>
</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>
<!-- 引入mybatis的映射文件-->
<mappers>
<!-- <mapper resource="mappers\UserMapper.xml"/>-->
<!-- 以包的形式引入,有注意点,要注意可能会出错-->
<package name="com.itzhh.mybatisOne.Mapper"/>
</mappers>
</configuration>
- 所需的jdbc.properties根据自己的实际情况进行配置
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
- 如果需要配置日志,在pom中引入相应依赖,同时创建log4j.xml
<?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>
- 创建Maven工程对应的目录结构
- 创建Mapper接口
package com.itzhh.mybatisOne.Mapper;
import com.itzhh.mybatisOne.Entity.User;
import java.util.List;
/**
* Author: zhh
* Date: 2022-12-21 10:48
* Description: <描述>
*/
public interface UserMapper {
int insertUser();
void updateUser();
void deleteUser();
User selectUserById();
List<User> selectAllUsers();
}
- 创建对应的mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itzhh.mybatisOne.Mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into t_user values(null,'admin','123456',23,'男','12345@qq.com')
</insert>
<update id="updateUser">
update t_user set username='zhh' where id = 2
</update>
<delete id="deleteUser">
delete from t_user where id = 4
</delete>
<select id="selectUserById" resultType="com.itzhh.mybatisOne.Entity.User">
select * from t_user where id = 3
</select>
<select id="selectAllUsers" resultType="com.itzhh.mybatisOne.Entity.User">
select * from t_user ;
</select>
</mapper>
注意:因为我在mybatis核心配置文件中是通过包形式引入mybatis依赖文件的,所以只需要完整类名和包名对应即可,不需要每次都引入。但要注意对应的包的位置和名字必须一致。
- 至此,一个简单的mybatis环境搭建完成。
- 获取sqlsession的工具类
package com.itzhh.mybatisOne.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;
/**
* Author: zhh
* Date: 2022-12-21 11:20
* Description: <描述>
*/
public class SqlSessionUtil {
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
//读取MyBatis的核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//创建SqlSession对象,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
//SqlSession sqlSession = sqlSessionFactory.openSession();
//创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交
sqlSession = sqlSessionFactory.openSession(true);
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
- 简单测试案例
package com.itzhh.mybatisOne;
import com.itzhh.mybatisOne.Entity.User;
import com.itzhh.mybatisOne.Mapper.UserMapper;
import com.itzhh.mybatisOne.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* Author: zhh
* Date: 2022-12-21 11:16
* Description: <描述>
*/
public class TestMybatis {
@Test
public void testInsert(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int result = mapper.insertUser();
sqlSession.close();
}
@Test
public void testDelete(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser();
sqlSession.close();
}
@Test
public void testUpdate(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.updateUser();
sqlSession.close();
}
@Test
public void testSelect(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById();
System.out.println(user);
sqlSession.close();
}
@Test
public void testSelectAll(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.selectAllUsers();
users.forEach(System.out::println);
sqlSession.close();
}
}
逆向工程的创建
- 在pom.xml中添加相应的依赖
<?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">
<parent>
<artifactId>SSM</artifactId>
<groupId>com.itzhh.ssm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis_mbg</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
<!-- 控制Maven在构建过程中相关配置 -->
<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>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
- 在resources下创建generatorConfig.xml
<?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>
<!--
targetRuntime: 执行生成的逆向工程的版本
MyBatis3Simple: 生成基本的CRUD(清新简洁版)
MyBatis3: 生成带条件的CRUD(奢华尊享版)
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 数据库的连接信息 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm?
serverTimezone=UTC"
userId="root"
password="123456">
</jdbcConnection>
<!-- javaBean的生成策略-->
<javaModelGenerator targetPackage="com.itzhh.mybatis.entity"
targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="com.itzhh.mybatis.mapper"
targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- Mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.itzhh.mybatis.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 逆向分析的表 -->
<!-- tableName设置为*号,可以对应所有表,此时不写domainObjectName -->
<!-- domainObjectName属性指定生成出来的实体类的类名 -->
<table tableName="t_emp" domainObjectName="Emp"/>
<table tableName="t_dept" domainObjectName="Dept"/>
</context>
</generatorConfiguration>
- 双击执行
- 逆向工程只是帮助生成了一部分代码,其它步骤照旧。
分页插件的使用
- 在pom.xml中添加相关依赖
<!-- 分页插件依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
- 在mybatis-config.xml中添加相关插件,注意放到environment标签之前
<!-- 设置分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>
- 在测试类中使用分页插件
package com.itzhh.mybatis;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itzhh.mybatis.entity.Emp;
import com.itzhh.mybatis.entity.EmpExample;
import com.itzhh.mybatis.mapper.EmpMapper;
import com.itzhh.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* Author: zhh
* Date: 2022-12-26 15:17
* Description: <描述>
*/
public class TestPage {
@Test
public void testPage(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
//查询之前开启分页功能
Page<Object> page = PageHelper.startPage(1, 4);
List<Emp> emps = mapper.selectByExample(null);
//查询功能之后可以获取分页相关的所有数据
PageInfo<Emp> pageInfo = new PageInfo<>(emps, 5);
emps.forEach(System.out::println);
System.out.println(pageInfo);
}
}
- 结果:
DEBUG 12-26 15:23:43,224 Cache Hit Ratio [SQL_CACHE]: 0.0 (LoggingCache.java:60)
DEBUG 12-26 15:23:43,293 ==> Preparing: SELECT count(0) FROM t_emp (BaseJdbcLogger.java:137)
DEBUG 12-26 15:23:43,315 ==> Parameters: (BaseJdbcLogger.java:137)
DEBUG 12-26 15:23:43,331 <== Total: 1 (BaseJdbcLogger.java:137)
DEBUG 12-26 15:23:43,333 ==> Preparing: select emp_id, emp_name, emp_age from t_emp LIMIT ? (BaseJdbcLogger.java:137)
DEBUG 12-26 15:23:43,333 ==> Parameters: 4(Integer) (BaseJdbcLogger.java:137)
DEBUG 12-26 15:23:43,334 <== Total: 4 (BaseJdbcLogger.java:137)
Emp{empId=1, empName='zhh', empAge=34}
Emp{empId=2, empName='zhh', empAge=34}
Emp{empId=3, empName='abc', empAge=null}
Emp{empId=4, empName='fcd', empAge=null}
PageInfo{pageNum=1, pageSize=4, size=4,
startRow=1, endRow=4, total=34, pages=9,
list=Page{count=true, pageNum=1, pageSize=4,
startRow=0, endRow=4, total=34, pages=9, reasonable=false, pageSizeZero=false}
[Emp{empId=1, empName='zhh', empAge=34},
Emp{empId=2, empName='zhh', empAge=34},
Emp{empId=3, empName='abc', empAge=null},
Emp{empId=4, empName='fcd', empAge=null}],
prePage=0, nextPage=2, isFirstPage=true,
isLastPage=false, hasPreviousPage=false,
hasNextPage=true, navigatePages=5,
navigateFirstPage=1, navigateLastPage=5,
navigatepageNums=[1, 2, 3, 4, 5]}