Mybatis的环境搭建:
1:搭建maven工程引入依赖
mybatis依赖 mybatisysql驱动包 mysql-connector-java 3:junit 单元测试 4:log4j打印日志
2:创建mybatis核心配置文件SqlMapConfig.xml
配置文件的结构 properties标签中可以定义属性值,也可以引入外部 配置文件。可以使用${name}获 取值。 setting的作用如缓存、延迟加 载、命名规则等
是配置MyBatis插件的 如page-helper分页插件 typeAliases 为包和类起别名。
-configuration
-properties(属性)
-property
-settings(全局配置参数)
-setting
-plugins(插件)
-plugin
-typeAliases(别名)
-typeAliase
-package
-environments(环境)
-environment
-transactionManager(事务管理)
-dataSource(数据源)
-mappers(映射器)
-mapper
-package
3:创建实体类
4:创建持久层接口和映射文件
在resource目录创建映射文件 将映射文件配置到mybatis核心配置文件中
映射文件的注意事项:
映射文件中namespace属性要写接口的全名。
映射文件中标签的id属性是接口方法的方法名。
映射文件中标签的resultType属性是接口方法的返回值类型。
映射文件中标签的parameterType属性是接口方法的参数类型。
映射文件中resultType、parameterType属性要写全类名, 如果是集合类型,则写其泛型的全类名。
5:使用mybatis控制数据库
@Test
public void testFindAll() throws Exception {
// (1)读取核心配置文件
InputStream is =
Resources.getResourceAsStream("SqlMapConfig.xml");
// (2)创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
// (3)SqlSessionFactoryBuilder对象获取SqlSessionFactory对象
SqlSessionFactory factory =
builder.build(is);
// (4)SqlSessionFactory对象获取SqlSession对象
SqlSession session =
factory.openSession();
// (5)SqlSession对象获取代理对象
UserMapper userMapper =
session.getMapper(UserMapper.class);
// (6)代理对象执行方法
List<User> all = userMapper.findAll();
all.forEach(System.out::println);
// (7)释放资源
session.close();
is.close();
}
mybatis的一些其他功能
主键回填 SELECT LAST_INSERT_ID():查询刚刚插入的记录的主键 值,只适用于自增主键,且必须和insert语句一起执行。
<insert id="add"
parameterType="com.czy.user.User">
<!-- keyProperty:主键属性名,keyColumn:主键列名,resultType:主键类型,order:执行时机 -->
<selectKey keyProperty="id"
keyColumn="id" resultType="int"
order="AFTER">
SELECT LAST_INSERT_ID();
</selectKey>
insert into
user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#
{address})
</insert>
映射文件的编写
MyBatis映射文件中除了select,insert,delete,update 外,还 有一些标签可以使用:resultMap
标签的作用的自定义映射关系。用于关联查询 封装对象,list,map,数组等
<sql> <include> 配合使用 前者提取重复的代码 后者引入代码
特殊字符处理 在sql中不要使用< > 等符号用实体代替符号
以及<if> <where> <foreach>等标签具体使用看mybatis官方文档。
关联查询
一对一关联查询 封装对象类型
查询学生时,将关联的一个班级对象查询出来,就是一对一关联查询。实体类如下
创建持久层
public interface StudentMapper {
List<Student> findAll();
}
映射文件resultMap的具体使用 封装对象用<association>
<resultMap id="studentMapper"
type="com.czy.pojo.Student">
<!-- 主键列 -->
<id property="sid" column="sid"></id>
<!-- 普通列 -->
<result property="name" column="name">
</result>
<result property="age" column="age">
</result>
<result property="sex" column="sex">
</result>
<!-- 一对一对象列 property:属性名 column:关
联列名 javaType:对象类型用association-->
<association property="classes"
column="classId"
javaType="com.czy.pojo.Classes">
<!-- 关联对象主键列 -->
<id property="cid" column="cid">
</id>
<!-- 关联对象普通列 -->
<result property="className"
column="className"></result>
</association>
</resultMap>
<!-- 多表查询,级联查询学生和其班级 -->
<select id="findAll"
resultMap="studentMapper">
select * from student left join classes
on student.classId = classes.cid;
</select>
一对多关联查询
查询班级时,将关联的学生集合查询出来,就是一对多关联查询。 与一对一的不同就是更换了主体表 把班级作为主表
创建持久层接口
public interface ClassesMapper {
List<Classes> findAll();
}
创建映射文件 封装集合 用collection
<resultMap id="classesMapper"
type="com.czy.pojo.Classes">
<id property="cid" column="cid"></id>
<result property="className"
column="className"></result>
<!-- 集合列 property:属性名 column:关联
列名 ofType:集合的泛型 -->
<collection property="studentList"
column="classId"
ofType="com.czy.pojo.Student">
<id property="sid" column="sid">
</id>
<result property="name"
column="name"></result>
<result property="age" column="age">
</result>
<result property="sex" column="sex">
</result>
</collection>
</resultMap>
<!-- 多表查询,级联查询班级和它的学生 -->
<select id="findAll"
resultMap="classesMapper">
select * from classes left join student
on classes.cid = student.classId;
</select>
多对多关联查询
多对多关联查询本质就是两个一对多关联查询。 例如有老师类和班级类: 一个老师对应多个班级,也就是老师类中有一个班级集合属性。 一个班级对应多个老师,也就是班级类中有一个老师集合属性。
<resultMap id="teacherMapper"
type="com.czy.pojo.Teacher">
<id column="tid" property="tid"></id>
<result column="tname" property="tname">
</result>
<collection property="classes"
column="tid"
ofType="com.czy.pojo.Classes">
<id column="cid" property="cid">
</id>
<result column="className"
property="className"></result>
</collection>
</resultMap>
<select id="findAll"
resultMap="teacherMapper">
select *
from teacher
left join classes_teacher
on teacher.tid = classes_teacher.tid
left join classes
on classes_teacher.cid = classes.cid
</select>
分页插件使用
引入依赖
<!-- PageHelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
2:Mybatis配置文件中配置PageHelper插件
<plugins>
<plugin
interceptor="com.github.pagehelper.PageInt
erceptor">
<!-- 设置数据库类型-->
<property name="helperDialect"
value="mysql"/>
</plugin>
</plugins>
使用PageHelper插件
@Test
public void testFindPage() {
// (1)查询前设置分页参数,参数一:页数,从1开始。参数二:每页条数
PageHelper.startPage(1, 3);
// (2)正常查询
List<User> all = userMapper.findAll();
// (3)创建页面对象,创建时将查询结果传入构造方法
PageInfo pageInfo = new PageInfo(all);
// (4)打印页面对象的属性
System.out.println("结果集:"+pageInfo.getList());
System.out.println("总条数:"+pageInfo.getTotal());
System.out.println("总页数"+pageInfo.getPages());
System.out.println("当前页"+pageInfo.getPageNum());
System.out.println("每页条数"+pageInfo.getSize());
}
MybatisGenerator使用
注意mbg的版本号和数据库连接包的版本号 不兼容会报错
1:准备数据库表 product表
2:在pom文件中配置MBG插件
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!-- MBG配置文件位置 -->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<!-- 运行显示详情 -->
<verbose>true</verbose>
<!-- 允许覆盖文件 -->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
3:编3写MBG配置文件
<?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>
<!-- jdbc的jar包位置,插件需要连接数据库 -->
<classPathEntry location="F:\repository\mysql\mysql-connector-java\8.0.26\mysql-connector-java-8.0.26.jar"/>
<context id="default" targetRuntime="MyBatis3">
<!-- 是否去除自动生成的注释-->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接参数-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="root"></jdbcConnection>
<!-- 类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:JAVA类路径 targetProject:生成的POJO类的包-->
<javaModelGenerator targetProject="src/main/java" targetPackage="com.czy.pojo">
<!-- 是否生成子包 -->
<property name="enableSubPackages" value="false"/>
<!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:配置文件路径 targetPackage:生成映射文件的位置 -->
<sqlMapGenerator targetProject="src/main/resources" targetPackage="com.czy.mapper">
<!-- 是否生成子包 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:JAVA类路径 targetProject:生成的持久层接口包 -->
<javaClientGenerator targetProject="src/main/java" targetPackage="com.czy.mapper" type="XMLMAPPER">
<!-- 是否生成子包 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 数据库表,表名不要和其他库中的表名一样 -->
<table tableName="product"></table>
</context>
</generatorConfiguration>
生成的文件
-
Product.java:POJO类
-
ProductMapper.java:持久层接口
-
ProductMapper.xml:映射文件
-
ProductExample.java:查询扩展类,该类可以构造复杂的查询条件。
- Criterion:代表一个字段。
- GeneratedCriteria:抽象类,生成查询条件的工具。
- Criteria:GeneratedCriteria的子类,生成查询条件的工具。
拓展类的使用 查询
Mybatis PDF