一、 DAO层的实现的规律

  • 实体类与数据表存在对应关系,并且是有规律的——只要知道了数据表的结构,就能够生成实体类;
  • 所有实体的DAO接口中定义的方法也是有规律的,不同点就是实体类型不同

    • UserDAO

      1. public interface UserDAO extends GeneralDAO<User>{
      2. public int insert(User t);
      3. }
    • GoodsDAO

      1. public interface GoodsDAO extends GeneralDAO<Goods> {
      2. public int insert(Goods t);
      3. }
    • GeneralDAO

      1. public interface GeneralDAO<T>{
      2. //通用方法
      3. public int insert(T t);
      4. public T queryOneByPrimarykey(int i);
      5. }
  • 对于GeneralDAO接口定义的数据库操作方法因为使用了泛型,无需映射文件;对于UserDAO和GoodsDAO需要映射文件,所有DAO的相同操作的映射文件也是有规律可循的

    • UserMapper

      1. <insert id="insert">
      2. insert into users(user_id,username) values(#{userId},#{username})
      3. </insert>

      ```java @Table(“users”) public class User{

      @Id @Column(“user_id”) private int userId;

      @Column(“username”) private String username;

}

  1. - GoodsMapper
  2. ```xml
  3. <insert id="insert">
  4. insert into goods(goods_id,goods_name) values(#{goodsId},#{goodsName})
  5. </insert>
  1. @Table("product")
  2. public class Goods{
  3. @Id
  4. @Column("goods_id")
  5. private int goodsId;
  6. @Column("goods_name")
  7. private String goodsName;
  8. }

二、tkMapper简介

基于MyBatis提供了很多第三方插件,这些插件通常可以完成数据操作方法的封装(GeneralDAO)、数据库逆向工程工作(根据数据表生成实体类、生成映射文件)

  • MyBatis-plus
  • tkMapper

tkMapper就是一个MyBatis插件,是在MyBatis的基础上提供了很多工具,让开发变得简单,提高开发效率。

  • 提供了针对单表通用的数据库操作方法
  • 逆向工程(根据数据表生成实体类、dao接口、映射文件)

三、tkMapper整合

3.1 基于SpringBoot完成MyBatis的整合

3.2 整合tkMapper(在beans中添加依赖)

3.2.1 添加tkMapper的依赖
  1. <dependency>
  2. <groupId>tk.mybatis</groupId>
  3. <artifactId>mapper-spring-boot-starter</artifactId>
  4. <version>2.1.5</version>
  5. </dependency>

3.2.2 修改启动类的@MapperScan注解的包
  • tk.mybatis.spring.annotation.MapperScan
  1. import tk.mybatis.spring.annotation.MapperScan;
  2. @SpringBootApplication
  3. @MapperScan("com.qfedu.tkmapperdemo.dao")
  4. public class TkmapperDemoApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(TkmapperDemoApplication.class, args);
  7. }
  8. }

四、tkMapper使用

4.1 创建数据表

  1. CREATE TABLE `users` (
  2. `user_id` int(64) NOT NULL AUTO_INCREMENT COMMENT '主键id 用户id',
  3. `username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名 用户名',
  4. `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码 密码',
  5. `nickname` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '昵称 昵称',
  6. `realname` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '真实姓名 真实姓名',
  7. `user_img` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '头像 头像',
  8. `user_mobile` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号 手机号',
  9. `user_email` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱地址 邮箱地址',
  10. `user_sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别 M(男) or F(女)',
  11. `user_birth` date NULL DEFAULT NULL COMMENT '生日 生日',
  12. `user_regtime` datetime(0) NOT NULL COMMENT '注册时间 创建时间',
  13. `user_modtime` datetime(0) NOT NULL COMMENT '更新时间 更新时间',
  14. PRIMARY KEY (`user_id`) USING BTREE
  15. ) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户 ' ROW_FORMAT = Compact;

4.2 创建实体类

  1. @Data
  2. @NoArgsConstructor
  3. @AllArgsConstructor
  4. public class User {
  5. private int userId;
  6. private String username;
  7. private String password;
  8. private String nickname;
  9. private String realname;
  10. private String userImg;
  11. private String userMobile;
  12. private String userEmail;
  13. private String userSex;
  14. private Date userBirth;
  15. private Date userRegtime;
  16. private Date userModtime;
  17. }

4.3 创建DAO接口

tkMapper已经完成了对单表的通用操作的封装,封装在Mapper接口和MySqlMapper接口;因此如果我们要完成对单表的操作,只需自定义DAO接口继承Mapper接口和MySqlMapper接口

  1. public interface UserDAO extends Mapper<User>, MySqlMapper<User> {
  2. }

4.4 测试

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest(classes = TkmapperDemoApplication.class)
  3. public class UserDAOTest {
  4. @Autowired
  5. private UserDAO userDAO;
  6. @Test
  7. public void test(){
  8. User user = new User();
  9. user.setUsername("aaaa");
  10. user.setPassword("1111");
  11. user.setUserImg("img/default.png");
  12. user.setUserRegtime(new Date());
  13. user.setUserModtime(new Date());
  14. int i = userDAO.insert(user);
  15. System.out.println(i);
  16. }
  17. }

五、tkMapper提供的方法(增删改)

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest(classes = TkmapperDemoApplication.class)
  3. public class CategoryDAOTest {
  4. @Autowired
  5. private CategoryDAO categoryDAO;
  6. @Test
  7. public void testInsert(){
  8. Category category = new Category(0,"测试类别3",1,0,"03.png","xixi","aaa.jpg","black");
  9. //int i = categoryDAO.insert(category);
  10. int i = categoryDAO.insertUseGeneratedKeys(category);
  11. System.out.println(category.getCategoryId());
  12. assertEquals(1,i);
  13. }
  14. @Test
  15. public void testUpdate(){
  16. Category category = new Category(48,"测试类别4",1,0,"04.png","heihei","aaa.jpg","black");
  17. int i = categoryDAO.updateByPrimaryKey(category);
  18. // 根据自定义条件修改,Example example就是封装条件的
  19. // int i1 = categoryDAO.updateByExample( Example example);
  20. assertEquals(1,i);
  21. }
  22. @Test
  23. public void testDelete(){
  24. int i = categoryDAO.deleteByPrimaryKey(48);
  25. // 根据条件删除
  26. //int i1 = categoryDAO.deleteByExample(Example example);
  27. assertEquals(1,i);
  28. }
  29. @Test
  30. public void testSelect1(){
  31. //查询所有
  32. List<Category> categories = categoryDAO.selectAll();
  33. for (Category category: categories) {
  34. System.out.println(category);
  35. }
  36. }
  37. @Test
  38. public void testSelect2(){
  39. //根据主键查询
  40. Category category = categoryDAO.selectByPrimaryKey(47);
  41. System.out.println(category);
  42. }
  43. @Test
  44. public void testSelect3(){
  45. //条件查询
  46. //1.创建一个Example封装 类别Category查询条件
  47. //2。
  48. Example example = new Example(Category.class);
  49. Example.Criteria criteria = example.createCriteria();
  50. criteria.andEqualTo("categoryLevel",1);
  51. //criteria.orEqualTo("categoryLevel",2);
  52. //criteria.andNotEqualTo("categoryLevel",1);
  53. criteria.orLike("categoryName","%干%");
  54. List<Category> categories = categoryDAO.selectByExample(example);
  55. for (Category category: categories) {
  56. System.out.println(category);
  57. }
  58. }
  59. @Test
  60. public void testSelect4(){
  61. //分页查询
  62. int pageNum = 2;
  63. int pageSize = 10;
  64. int start = (pageNum-1)*pageSize;
  65. RowBounds rowBounds = new RowBounds(start,pageSize);
  66. List<Category> categories = categoryDAO.selectByRowBounds(new Category(), rowBounds);
  67. for (Category category: categories) {
  68. System.out.println(category);
  69. }
  70. //查询总记录数
  71. int i = categoryDAO.selectCount(new Category());
  72. System.out.println(i);
  73. }
  74. @Test
  75. public void testSelect5(){
  76. //带条件分页
  77. //条件
  78. Example example = new Example(Category.class);
  79. Example.Criteria criteria = example.createCriteria();
  80. criteria.andEqualTo("categoryLevel",1);
  81. //分页
  82. int pageNum = 2;
  83. int pageSize = 3;
  84. int start = (pageNum-1)*pageSize;
  85. RowBounds rowBounds = new RowBounds(start,pageSize);
  86. List<Category> categories = categoryDAO.selectByExampleAndRowBounds(example,rowBounds);
  87. for (Category category: categories) {
  88. System.out.println(category);
  89. }
  90. //查询总记录数(满足条件)
  91. int i = categoryDAO.selectCountByExample(example);
  92. System.out.println(i);
  93. }
  94. }

六、在使用tkMapper是如何进行关联查询

6.1 所有的关联查询都可以通过多个单表操作实现

  1. //查询用户同时查询订单
  2. Example example = new Example(User.class);
  3. Example.Criteria criteria = example.createCriteria();
  4. criteria.andEqualTo("username","zhangsan");
  5. //根据用户名查询用户
  6. //1.先根据用户名查询用户信息
  7. List<User> users = userDAO.selectByExample(example);
  8. User user = users.get(0);
  9. //2.再根据用户id到订单表查询订单
  10. Example example1 = new Example(Orders.class);
  11. Example.Criteria criteria1 = example1.createCriteria();
  12. criteria1.andEqualTo("userId",user.getUserId());
  13. List<Orders> ordersList = orderDAO.selectByExample(example1);
  14. //3.将查询到订单集合设置到user
  15. user.setOrdersList(ordersList);
  16. System.out.println(user);

6.2 自定义连接查询

  • 在使用tkMapper,DAO继承Mapper和MySqlMapper之后,还可以自定义查询

6.2.1 在DAO接口自定义方法
  1. public interface UserDAO extends GeneralDAO<User> {
  2. public User selectByUsername(String username);
  3. }

6.2.2 创建Mapper文件
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.qfedu.fmmall.dao.UserDAO">
  6. <insert id="insertUser">
  7. insert into users(username,password,user_img,user_regtime,user_modtime)
  8. values(#{username},#{password},#{userImg},#{userRegtime},#{userModtime})
  9. </insert>
  10. <resultMap id="userMap" type="User">
  11. <id column="user_id" property="userId"/>
  12. <result column="username" property="username"/>
  13. <result column="password" property="password"/>
  14. <result column="nickname" property="nickname"/>
  15. <result column="realname" property="realname"/>
  16. <result column="user_img" property="userImg"/>
  17. <result column="user_mobile" property="userMobile"/>
  18. <result column="user_email" property="userEmail"/>
  19. <result column="user_sex" property="userSex"/>
  20. <result column="user_birth" property="userBirth"/>
  21. <result column="user_regtime" property="userRegtime"/>
  22. <result column="user_modtime" property="userModtime"/>
  23. </resultMap>
  24. <select id="queryUserByName" resultMap="userMap">
  25. select
  26. user_id,
  27. username,
  28. password,
  29. nickname,
  30. realname,
  31. user_img,
  32. user_mobile,
  33. user_email,
  34. user_sex,
  35. user_birth,
  36. user_regtime,
  37. user_modtime
  38. from users
  39. where username=#{name}
  40. </select>
  41. </mapper>

七、逆向工程

逆向工程,根据创建好的数据表,生成实体类、DAO、映射文件

7.1 添加逆向工程依赖

是依赖是一个mybatis的maven插件,在mapper中添加

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.mybatis.generator</groupId>
  5. <artifactId>mybatis-generator-maven-plugin</artifactId>
  6. <version>1.3.5</version>
  7. <dependencies>
  8. <dependency>
  9. <groupId>mysql</groupId>
  10. <artifactId>mysql-connector-java</artifactId>
  11. <version>5.1.47</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>tk.mybatis</groupId>
  15. <artifactId>mapper</artifactId>
  16. <version>3.4.4</version>
  17. </dependency>
  18. </dependencies>
  19. </plugin>
  20. </plugins>
  21. </build>

7.2 逆向工程配置

  • 在resources/generator目录下创建generatorConfig.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <!-- 引入数据库连接配置 -->
  7. <!-- <properties resource="jdbc.properties"/>-->
  8. <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
  9. <property name="beginningDelimiter" value="`"/>
  10. <property name="endingDelimiter" value="`"/>
  11. <!-- 配置 GeneralDAO -->
  12. <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
  13. <property name="mappers" value="com.qfedu.tkmapperdemo.general.GeneralDAO"/>
  14. </plugin>
  15. <!-- 配置数据库连接 -->
  16. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  17. connectionURL="jdbc:mysql://localhost:3306/fmmall2"
  18. userId="root" password="admin123">
  19. </jdbcConnection>
  20. <!-- 配置实体类存放路径 -->
  21. <javaModelGenerator targetPackage="com.qfedu.tkmapperdemo.beans" targetProject="src/main/java"/>
  22. <!-- 配置 XML 存放路径 -->
  23. <sqlMapGenerator targetPackage="/" targetProject="src/main/resources/mappers"/>
  24. <!-- 配置 DAO 存放路径 -->
  25. <javaClientGenerator targetPackage="com.qfedu.tkmapperdemo.dao" targetProject="src/main/java" type="XMLMAPPER"/>
  26. <!-- 配置需要指定生成的数据库和表,% 代表所有表 -->
  27. <table tableName="%">
  28. <!-- mysql 配置 -->
  29. <!-- <generatedKey column="id" sqlStatement="Mysql" identity="true"/>-->
  30. </table>
  31. <!-- <table tableName="tb_roles">-->
  32. <!-- &lt;!&ndash; mysql 配置 &ndash;&gt;-->
  33. <!-- <generatedKey column="roleid" sqlStatement="Mysql" identity="true"/>-->
  34. <!-- </table>-->
  35. <!-- <table tableName="tb_permissions">-->
  36. <!-- &lt;!&ndash; mysql 配置 &ndash;&gt;-->
  37. <!-- <generatedKey column="perid" sqlStatement="Mysql" identity="true"/>-->
  38. <!-- </table>-->
  39. </context>
  40. </generatorConfiguration>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5. <generatorConfiguration>
  6. <!-- 引入数据库连接配置 -->
  7. <!--<properties resource="jdbc.properties"/>-->
  8. <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
  9. <property name="beginningDelimiter" value="`"/>
  10. <property name="endingDelimiter" value="`"/>
  11. <!-- 配置 GeneralDAO -->
  12. <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
  13. <property name="mappers" value="com.chang.ygmall.general.GeneralDAO"/>
  14. </plugin>
  15. <!-- 配置数据库连接 -->
  16. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  17. connectionURL="jdbc:mysql://localhost:3306/ygmall"
  18. userId="root" password="mysql">
  19. </jdbcConnection>
  20. <!-- 配置实体类存放路径 -->
  21. <javaModelGenerator targetPackage="com.chang.ygmall.entity" targetProject="src/main/java"/>
  22. <!-- 配置 XML 存放路径 -->
  23. <sqlMapGenerator targetPackage="/" targetProject="src/main/resources/mappers"/>
  24. <!-- 配置 DAO 存放路径 -->
  25. <javaClientGenerator targetPackage="com.chang.ygmall.dao" targetProject="src/main/java" type="XMLMAPPER"/>
  26. <!-- 配置需要指定生成的数据库和表,% 代表所有表 -->
  27. <table tableName="%">
  28. <!-- mysql 配置 -->
  29. <!-- <generatedKey column="id" sqlStatement="Mysql" identity="true"/>-->
  30. </table>
  31. <!-- <table tableName="tb_roles">-->
  32. <!-- &lt;!&ndash; mysql 配置 &ndash;&gt;-->
  33. <!-- <generatedKey column="roleid" sqlStatement="Mysql" identity="true"/>-->
  34. <!-- </table>-->
  35. <!-- <table tableName="tb_permissions">-->
  36. <!-- &lt;!&ndash; mysql 配置 &ndash;&gt;-->
  37. <!-- <generatedKey column="perid" sqlStatement="Mysql" identity="true"/>-->
  38. <!-- </table>-->
  39. </context>
  40. </generatorConfiguration>

7.3 将配置文件设置到逆向工程的maven插件

  1. <configuration>
  2. <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
  3. </configuration>

image.png

7.4 执行逆向生成

image.png