⼀、 DAO 层的实现的规律
实体类与数据表存在对应关系,并且是有规律的 —— 只要知道了数据表的结构,就能够
⽣成实体类;
所有实体的 DAO 接⼝中定义的⽅法也是有规律的,不同点就是实体类型不同
UserDAO
public interface UserDAO extends GeneralDAO<User>{
public int insert(User t);
}
GoodsDAO
public interface GoodsDAO extends GeneralDAO<Goods> {
public int insert(Goods t);
}
GeneralDAO
public interface GeneralDAO<T>{
//通⽤⽅法
public int insert(T t);
public T queryOneByPrimarykey(int i);
}
对于 GeneralDAO 接⼝定义的数据库操作⽅法因为使⽤了泛型, ⽆需映射⽂件 ;对于
UserDAO 和 GoodsDAO 需要映射⽂件,所有 DAO 的相同操作的映射⽂件也是有规律可循
的
UserMapper
<insert id="insert">
insert into users(user_id,username) values(#{userId},#
{username})
</insert>
@Table("users")
public class User{
@Id
@Column("user_id")
private int userId;
@Column("username")
private String username;
}
GoodsMapper
<insert id="insert">
insert into goods(goods_id,goods_name) values(#{goodsId},#
{goodsName})
</insert>
@Table("product")
public class Goods{
@Id
@Column("goods_id")
private int goodsId;
@Column("goods_name")
private String goodsName;
}
⼆、 tkMapper 简介
基于 MyBatis 提供了很多第三⽅插件,这些插件通常可以完成数据操作⽅法的封装
( GeneralDAO )、数据库逆向⼯程⼯作 ( 根据数据表⽣成实体类、⽣成映射⽂件 )
MyBatis-plus
tkMapper
tkMapper 就是⼀个 MyBatis 插件,是在 MyBatis 的基础上提供了很多⼯具,让开发变得简
单,提⾼开发效率。
提供了针对单表通⽤的数据库操作⽅法
逆向⼯程(根据数据表⽣成实体类、 dao 接⼝、映射⽂件)
三、 tkMapper 整合
3.1 基于 SpringBoot 完成 MyBatis 的整合
3.2 整合 tkMapper
3.2.1 添加 tkMapper 的依赖
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
3.2.2 修改启动类的 @MapperScan 注解的包
为 tk.mybatis.spring.annotation.MapperScan
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("com.qfedu.tkmapperdemo.dao")
public class TkmapperDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TkmapperDemoApplication.class, args);
}
}
四、 tkMapper 使⽤
4.1 创建数据表
CREATE TABLE `users` (
`user_id` int(64) NOT NULL AUTO_INCREMENT COMMENT '主键id ⽤户id',
`username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT
NULL COMMENT '⽤户名 ⽤户名',
`password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT
NULL COMMENT '密码 密码',
`nickname` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci
NULL DEFAULT NULL COMMENT '昵称 昵称',
`realname` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci
NULL DEFAULT NULL COMMENT '真实姓名 真实姓名',
`user_img` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci
NOT NULL COMMENT '头像 头像',
`user_mobile` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci
NULL DEFAULT NULL COMMENT '⼿机号 ⼿机号',
`user_email` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci
NULL DEFAULT NULL COMMENT '邮箱地址 邮箱地址',
`user_sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
DEFAULT NULL COMMENT '性别 M(男) or F(⼥)',
`user_birth` date NULL DEFAULT NULL COMMENT '⽣⽇ ⽣⽇',
`user_regtime` datetime(0) NOT NULL COMMENT '注册时间 创建时间',
`user_modtime` datetime(0) NOT NULL COMMENT '更新时间 更新时间',
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE =
utf8_general_ci COMMENT = '⽤户 ' ROW_FORMAT = Compact;
4.2 创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int userId;
private String username;
private String password;
private String nickname;
private String realname;
private String userImg;
private String userMobile;
private String userEmail;
private String userSex;
private Date userBirth;
private Date userRegtime;
private Date userModtime;
}
4.3 创建 DAO 接⼝
tkMapper 已经完成了对单表的通⽤操作的封装,封装在 Mapper 接⼝和 MySqlMapper 接
⼝;因此如果我们要完成对单表的操作,只需⾃定义 DAO 接⼝继承 Mapper 接⼝和
MySqlMapper 接⼝
public interface UserDAO extends Mapper<User>, MySqlMapper<User> {
}
4.4 测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TkmapperDemoApplication.class)
public class UserDAOTest {
@Autowired
private UserDAO userDAO;
@Test
public void test(){
User user = new User();
user.setUsername("aaaa");
user.setPassword("1111");
user.setUserImg("img/default.png");
user.setUserRegtime(new Date());
user.setUserModtime(new Date());
int i = userDAO.insert(user);
System.out.println(i);
}
}
五、 tkMapper 提供的⽅法
@SpringBootTest(classes = TkmapperDemoApplication.class)
public class CategoryDAOTest {
@Autowired
private CategoryDAO categoryDAO;
@Test
public void testInsert(){
Category category = new Category(0,"测试类3",1,0,"03.png","xixi","aaa.jpg","black");
//int i = categoryDAO.insert(category);
int i = categoryDAO.insertUseGeneratedKeys(category);
System.out.println(category.getCategoryId());
assertEquals(1,i);
}
@Test
public void testUpdate(){
Category category = new Category(48,"测试类别 4",1,0,"04.png","heihei","aaa.jpg","black");
int i = categoryDAO.updateByPrimaryKey(category);
// 根据⾃定义条件修改,Example example就是封装条件的
// int i1 = categoryDAO.updateByExample( Example example);
assertEquals(1,i);
}
@Test
public void testDelete(){
int i = categoryDAO.deleteByPrimaryKey(48);
// 根据条件删除
//int i1 = categoryDAO.deleteByExample(Example example);
assertEquals(1,i);
}
@Test
public void testSelect1(){
//查询所有
List<Category> categories = categoryDAO.selectAll();
for (Category category: categories) {
System.out.println(category);
}
}
@Test
public void testSelect2(){
//根据主键查询
Category category = categoryDAO.selectByPrimaryKey(47);
System.out.println(category);
}
@Test
public void testSelect3(){
//条件查询
//1.创建⼀个Example封装 类别Category查询条件
Example example = new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("categoryLevel",1);
criteria.orLike("categoryName","%⼲%");
List<Category> categories =
categoryDAO.selectByExample(example);
for (Category category: categories) {
System.out.println(category);
}
}
@Test
public void testSelect4(){
//分⻚查询
int pageNum = 2;
int pageSize = 10;
int start = (pageNum-1)*pageSize;
RowBounds rowBounds = new RowBounds(start,pageSize);
List<Category> categories = categoryDAO.selectByRowBounds(new
Category(), rowBounds);
for (Category category: categories) {
System.out.println(category);
}
//查询总记录数
int i = categoryDAO.selectCount(new Category());
System.out.println(i);
}
@Test
public void testSelect5(){
//带条件分⻚
//条件
Example example = new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("categoryLevel",1);
//分⻚
int pageNum = 2;
int pageSize = 3;
int start = (pageNum-1)*pageSize;
RowBounds rowBounds = new RowBounds(start,pageSize);
List<Category> categories =
categoryDAO.selectByExampleAndRowBounds(example,rowBounds);
for (Category category: categories) {
System.out.println(category);
}
//查询总记录数(满⾜条件)
int i = categoryDAO.selectCountByExample(example);
System.out.println(i);
}
}
六、在使⽤tkMapper是如何进⾏关联查询
6.1 所有的关联查询都可以通过多个单表操作实现
//查询⽤户同时查询订单
Example example = new Example(User.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("username","zhangsan");
//根据⽤户名查询⽤户
//1.先根据⽤户名查询⽤户信息
List<User> users = userDAO.selectByExample(example);
User user = users.get(0);
//2.再根据⽤户id到订单表查询订单
Example example1 = new Example(Orders.class);
Example.Criteria criteria1 = example1.createCriteria();
criteria1.andEqualTo("userId",user.getUserId());
List<Orders> ordersList = orderDAO.selectByExample(example1);
//3.将查询到订单集合设置到user
user.setOrdersList(ordersList);
System.out.println(user);
6.2 ⾃定义连接查询
在使⽤ tkMapper,DAO 继承 Mapper 和 MySqlMapper 之后,还可以⾃定义查询
6.2.1 在 DAO 接⼝⾃定义⽅法
public interface UserDAO extends GeneralDAO<User> {
public User selectByUsername(String username);
}
6.2.2 创建 Mapper ⽂件
<?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.qfedu.fmmall.dao.UserDAO">
<insert id="insertUser">
insert into
users(username,password,user_img,user_regtime,user_modtime)
values(#{username},#{password},#{userImg},#{userRegtime},#
{userModtime})
</insert>
<resultMap id="userMap" type="User">
<id column="user_id" property="userId"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="nickname" property="nickname"/>
<result column="realname" property="realname"/>
<result column="user_img" property="userImg"/>
<result column="user_mobile" property="userMobile"/>
<result column="user_email" property="userEmail"/>
<result column="user_sex" property="userSex"/>
<result column="user_birth" property="userBirth"/>
<result column="user_regtime" property="userRegtime"/>
<result column="user_modtime" property="userModtime"/>
</resultMap>
<select id="queryUserByName" resultMap="userMap">
select
user_id,
username,
password,
nickname,
realname,
user_img,
user_mobile,
user_email,
user_sex,
user_birth,
user_regtime,
user_modtime
from users
where username=#{name}
</select>
</mapper>
七、逆向⼯程
逆向⼯程,根据创建好的数据表,⽣成实体类、 DAO 、映射⽂件
7.1 添加逆向⼯程依赖
是依赖是⼀个 mybatis 的 maven 插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.4</version>
</dependency>
</dependencies>
</plugin>
7.2 逆向⼯程配置
在resources/generator⽬录下创建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>
<!-- 引⼊数据库连接配置 -->
<!-- <properties resource="jdbc.properties"/>-->
<context id="Mysql" targetRuntime="MyBatis3Simple"
defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<!-- 配置 GeneralDAO -->
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers"
value="com.qfedu.tkmapperdemo.general.GeneralDAO"/>
</plugin>
<!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/fmmall2"
userId="root" password="admin123">
</jdbcConnection>
<!-- 配置实体类存放路径 -->
<javaModelGenerator
targetPackage="com.qfedu.tkmapperdemo.beans"
targetProject="src/main/java"/>
<!-- 配置 XML 存放路径 -->
<sqlMapGenerator targetPackage="/"
targetProject="src/main/resources/mappers"/>
<!-- 配置 DAO 存放路径 -->
<javaClientGenerator targetPackage="com.qfedu.tkmapperdemo.dao"
targetProject="src/main/java" type="XMLMAPPER"/>
<!-- 配置需要指定⽣成的数据库和表,% 代表所有表 -->
<table tableName="%">
<!-- mysql 配置 -->
<!-- <generatedKey column="id" sqlStatement="Mysql"
identity="true"/>-->
</table>
<!-- <table tableName="tb_roles">-->
<!-- <!– mysql 配置 –>-->
<!-- <generatedKey column="roleid" sqlStatement="Mysql"
identity="true"/>-->
<!-- </table>-->
<!-- <table tableName="tb_permissions">-->
<!-- <!– mysql 配置 –>-->
<!-- <generatedKey column="perid" sqlStatement="Mysql"
identity="true"/>-->
<!-- </table>-->
</context>
</generatorConfiguration>
7.3 将配置⽂件设置到逆向⼯程的maven插件
7.4 执⾏逆向⽣成