• Mybatis01


    目录

    一、mybatis环境搭建

    1、导入pom.xml依赖

    2、导入框架的配置文件

    二、Mybatis generator插件的使用

    三、Mybatis增删改查测试

    一、mybatis环境搭建

    1、导入pom.xml依赖

    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    3. <parent>
    4. <artifactId>ideamavenartifactId>
    5. <groupId>org.examplegroupId>
    6. <version>1.0-SNAPSHOTversion>
    7. parent>
    8. <modelVersion>4.0.0modelVersion>
    9. <artifactId>mybatis01artifactId>
    10. <packaging>warpackaging>
    11. <name>mybatis01 Maven Webappname>
    12. <url>http://www.example.comurl>
    13. <properties>
    14. <maven.compiler.source>1.8maven.compiler.source>
    15. <maven.compiler.target>1.8maven.compiler.target>
    16. properties>
    17. <dependencies>
    18. <dependency>
    19. <groupId>junitgroupId>
    20. <artifactId>junitartifactId>
    21. <version>4.12version>
    22. <scope>testscope>
    23. dependency>
    24. <dependency>
    25. <groupId>javax.servletgroupId>
    26. <artifactId>javax.servlet-apiartifactId>
    27. <version>4.0.0version>
    28. <scope>providedscope>
    29. dependency>
    30. <dependency>
    31. <groupId>org.mybatisgroupId>
    32. <artifactId>mybatisartifactId>
    33. <version>3.4.5version>
    34. dependency>
    35. <dependency>
    36. <groupId>mysqlgroupId>
    37. <artifactId>mysql-connector-javaartifactId>
    38. <version>5.1.44version>
    39. dependency>
    40. <dependency>
    41. <groupId>org.apache.logging.log4jgroupId>
    42. <artifactId>log4j-coreartifactId>
    43. <version>2.9.1version>
    44. dependency>
    45. <dependency>
    46. <groupId>org.apache.logging.log4jgroupId>
    47. <artifactId>log4j-apiartifactId>
    48. <version>2.9.1version>
    49. dependency>
    50. <dependency>
    51. <groupId>org.apache.logging.log4jgroupId>
    52. <artifactId>log4j-webartifactId>
    53. <version>2.9.1version>
    54. dependency>
    55. dependencies>
    56. <build>
    57. <finalName>mybatis01finalName>
    58. <resources>
    59. <resource>
    60. <directory>src/main/javadirectory>
    61. <includes>
    62. <include>**/*.xmlinclude>
    63. includes>
    64. resource>
    65. <resource>
    66. <directory>src/main/resourcesdirectory>
    67. <includes>
    68. <include>jdbc.propertiesinclude>
    69. <include>*.xmlinclude>
    70. includes>
    71. resource>
    72. resources>
    73. <pluginManagement>
    74. <plugins>
    75. <plugin>
    76. <groupId>org.mybatis.generatorgroupId>
    77. <artifactId>mybatis-generator-maven-pluginartifactId>
    78. <version>1.3.2version>
    79. <dependencies>
    80. <dependency>
    81. <groupId>mysqlgroupId>
    82. <artifactId>mysql-connector-javaartifactId>
    83. <version>5.1.44version>
    84. dependency>
    85. dependencies>
    86. <configuration>
    87. <overwrite>trueoverwrite>
    88. configuration>
    89. plugin>
    90. <plugin>
    91. <artifactId>maven-clean-pluginartifactId>
    92. <version>3.1.0version>
    93. plugin>
    94. <plugin>
    95. <artifactId>maven-resources-pluginartifactId>
    96. <version>3.0.2version>
    97. plugin>
    98. <plugin>
    99. <artifactId>maven-compiler-pluginartifactId>
    100. <version>3.8.0version>
    101. plugin>
    102. <plugin>
    103. <artifactId>maven-surefire-pluginartifactId>
    104. <version>2.22.1version>
    105. plugin>
    106. <plugin>
    107. <artifactId>maven-war-pluginartifactId>
    108. <version>3.2.2version>
    109. plugin>
    110. <plugin>
    111. <artifactId>maven-install-pluginartifactId>
    112. <version>2.5.2version>
    113. plugin>
    114. <plugin>
    115. <artifactId>maven-deploy-pluginartifactId>
    116. <version>2.8.2version>
    117. plugin>
    118. plugins>
    119. pluginManagement>
    120. build>
    121. project>

    补全maven项目的目录,如图:

     resources中jdbc.properties 数据库连接配置

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=123456

    2、导入框架的配置文件

    安装以下插件

    Free mybatis plugin

    Mybatis generator

    mybatis tools

    maven helper 

    详细介绍

    Intellij Idea Mybatis 插件(plugin和tools插件)_yangshijin1988的博客-CSDN博客_idea mapper 插件

     

     

     

     下载maven helper之后 可以看到配置文件中所用的依赖

     修改web.xml

    1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    4. version="3.1">
    5. web-app>

     mybatis.cfg.xml

    1. configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    2. <configuration>
    3. <properties resource="jdbc.properties"/>
    4. <settings>
    5. <setting name="logImpl" value="LOG4J2"/>
    6. settings>
    7. <typeAliases>
    8. typeAliases>
    9. <environments default="development">
    10. <environment id="development">
    11. <transactionManager type="jdbc"/>
    12. <dataSource type="POOLED">
    13. <property name="driver"
    14. value="${jdbc.driver}"/>
    15. <property name="url"
    16. value="${jdbc.url}"/>
    17. <property name="username" value="${jdbc.username}"/>
    18. <property name="password" value="${jdbc.password}"/>
    19. dataSource>
    20. environment>
    21. environments>
    22. <mappers>
    23. mappers>
    24. configuration>

    二、Mybatis generator插件的使用

    基于ssm的逆向工程使用

    1. 安装Mybatis generator插件 已下载安装好
    2. 配置generatorConfig.xml
    3. 配置maven运行generator命令
    4. 在pom中处理generatorConfig.xml不能编译问题

     generatorConfig.xml

    1. generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    2. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
    3. <generatorConfiguration>
    4. <properties resource="jdbc.properties"/>
    5. <classPathEntry location="E:\\cdl_mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    6. <context id="infoGuardian">
    7. <commentGenerator>
    8. <property name="suppressAllComments" value="true"/>
    9. <property name="suppressDate" value="true"/>
    10. commentGenerator>
    11. <jdbcConnection driverClass="${jdbc.driver}"
    12. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    13. <javaTypeResolver>
    14. <property name="forceBigDecimals" value="false"/>
    15. javaTypeResolver>
    16. <javaModelGenerator targetPackage="com.cdl.model"
    17. targetProject="src/main/java">
    18. <property name="enableSubPackages" value="false"/>
    19. <property name="constructorBased" value="true"/>
    20. <property name="trimStrings" value="false"/>
    21. <property name="immutable" value="false"/>
    22. javaModelGenerator>
    23. <sqlMapGenerator targetPackage="com.cdl.mapper"
    24. targetProject="src/main/java">
    25. <property name="enableSubPackages" value="false"/>
    26. sqlMapGenerator>
    27. <javaClientGenerator targetPackage="com.cdl.mapper"
    28. targetProject="src/main/java" type="XMLMAPPER">
    29. <property name="enableSubPackages" value="false"/>
    30. javaClientGenerator>
    31. <table schema="" tableName="t_mvc_Book" domainObjectName="Book"
    32. enableCountByExample="false" enableDeleteByExample="false"
    33. enableSelectByExample="false" enableUpdateByExample="false">
    34. table>
    35. <table schema="" tableName="t_oa_permission" domainObjectName="Permission"
    36. enableCountByExample="false" enableDeleteByExample="false"
    37. enableSelectByExample="false" enableUpdateByExample="false">
    38. table>
    39. context>
    40. generatorConfiguration>

    写命令

     

     写入命令

     

     结果

     写入命令后运行会自动将数据库的表、字段名 映射成对应的类名和属性名

    并且生成增删改查的方法

    总结一下:

    1.添加配置文件

      1.1 修改5.1.44的jar的路径

      1.2 修改实体类生成的地址

      1.3 修改SQL对应的配置文件的生成地址

      1.4修改Dao层代码地址

      1.5指定需要生成增删改查代码对应的表

    2.配置maven的mybatis逆向生成代码的命令

    commond line

    3.在pom文件中使用配置好的命令

    三、Mybatis增删改查测试

    sqlsession的作用:

    1.sqlsession可以拿到mapper对象

    2.作为缓存使用,一级缓存,默认会开启的缓存、

    3.出于对性能的考虑,会采用二级缓存,二级缓存需要手动开启

    测试逆向生成的代码是否正确

      有事务的:增删改

      无事务的:查询

    只需要测 查询和删除 即可知道是否正确

    建一个com.cdl.biz.impl的包

    1. package com.cdl.biz;
    2. import com.cdl.model.Book;
    3. /**
    4. * @author cdl
    5. * @site www.cdl.com
    6. * @create 2022-08-10 22:00
    7. */
    8. public interface BookBiz {
    9. int deleteByPrimaryKey(Integer bid);
    10. Book selectByPrimaryKey(Integer bid);
    11. }

    com.cdl.util

    SessionUtil 

    1. package com.cdl.util;
    2. import org.apache.ibatis.session.SqlSession;
    3. import org.apache.ibatis.session.SqlSessionFactory;
    4. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    5. /**
    6. * @author cdl
    7. * @site www.cdl.com
    8. * @create 2022-08-10 22:47
    9. */
    10. public class SessionUtil {
    11. private static SqlSessionFactory sessionFactory;
    12. private static ThreadLocal threadLocal = new ThreadLocal();
    13. static {
    14. sessionFactory = new SqlSessionFactoryBuilder().build(SessionUtil.class.getResourceAsStream("/mybatis.cfg.xml"));
    15. }
    16. public static SqlSession openSession() {
    17. SqlSession session = threadLocal.get();
    18. if (null == session) {
    19. session = sessionFactory.openSession();
    20. threadLocal.set(session);
    21. }
    22. return session;
    23. }
    24. public static void main(String[] args) {
    25. SqlSession session = openSession();
    26. System.out.println(session.getConnection());
    27. session.close();
    28. // System.out.println(session.getConnection());
    29. }
    30. }
    //alt + insert 快速提供set/get/tostring/构造函数
    //alt +enter 快速构建实现类 能够自动补全

     test类:
     

    1. package com.cdl.biz.impl;
    2. import org.junit.After;
    3. import org.junit.Before;
    4. import org.junit.Test;
    5. import static org.junit.Assert.*;
    6. /**
    7. * @author cdl
    8. * @site www.cdl.com
    9. * @create 2022-08-10 22:55
    10. */
    11. public class BookBizImplTest {
    12. @Before
    13. public void setUp() throws Exception {
    14. System.out.println("初始换方法。。。");
    15. }
    16. @After
    17. public void tearDown() throws Exception {
    18. System.out.println("方法测试结束。。");
    19. }
    20. @Test
    21. public void deleteByPrimaryKey() {
    22. }
    23. @Test
    24. public void selectByPrimaryKey() {
    25. System.out.println("测试的业务方法。。。");
    26. }
    27. }

    运行结果:

     修改配置文件 mybatis.cfg.xml

    
       
    

     测试类:

    1. package com.cdl.biz.impl;
    2. import com.cdl.mapper.BookMapper;
    3. import com.cdl.util.SessionUtil;
    4. import org.apache.ibatis.session.SqlSession;
    5. import org.junit.After;
    6. import org.junit.Before;
    7. import org.junit.Test;
    8. /**
    9. * @author cdl
    10. * @site www.cdl.com
    11. * @create 2022-08-10 22:55
    12. */
    13. public class BookBizImplTest {
    14. private BookBizImpl bookBiz;
    15. SqlSession sqlSession;
    16. @Before
    17. public void setUp() throws Exception {
    18. System.out.println("初始换方法。。。");
    19. BookBizImpl bookBiz = new BookBizImpl();
    20. //工具类中获取session对象
    21. sqlSession = SessionUtil.openSession();
    22. //从session对象中获取mapper对象
    23. BookMapper mapper = sqlSession.getMapper(BookMapper.class);
    24. bookBiz.setBookMapper(mapper);
    25. this.bookBiz = bookBiz;
    26. }
    27. @After
    28. public void tearDown() throws Exception {
    29. System.out.println("方法测试结束。。");
    30. }
    31. @Test
    32. public void deleteByPrimaryKey() {
    33. }
    34. @Test
    35. public void selectByPrimaryKey() {
    36. System.out.println("测试的业务方法。。。");
    37. //System.out.println(bookBiz.getBookMapper());
    38. System.out.println(bookBiz.selectByPrimaryKey(44));
    39. }
    40. }

     

  • 相关阅读:
    FlinkSQL开发经验分享
    Linux系统编程(三)——Linux下的进程
    Java核心篇,二十三种设计模式(十三),行为型——责任链模式
    如何免费压缩图片-批量免费压缩图片大小的软件
    GNU 简单介绍(含glibc 源码下载)
    算法专题篇四:前缀和
    调用网络时报错name weight already exists
    微信小程序案例2-3:婚礼邀请函
    LeetCode第14题:最长公共前缀
    idea里面mysql数据库统一配置文件和存放到集合中读取出来详细步骤
  • 原文地址:https://blog.csdn.net/weixin_62735525/article/details/126263287