• mybatis入门


    目录

    一、mabatis

    二、Mybatis环境搭建

    1)导入pom依赖

     2)导入框架的配置文件

    三、Mybatis generator插件的使用

    四、Mybatis增删改查测试


    一、mabatis

    简介:是一款orm框架,即对象映射关系框架;是一款关于数据库层面的框架

    官网:MyBatis中文网

    ORM:Object reference Mapping 

    二、Mybatis环境搭建

    1)导入pom依赖

    ①、先建立一个maven项目,然后导入pom依赖

     将以上图中蓝色部分的代码块替换为以下这个

    1. <properties>
    2. <maven.compiler.source>1.8maven.compiler.source>
    3. <maven.compiler.target>1.8maven.compiler.target>
    4. properties>
    5. <dependencies>
    6. <dependency>
    7. <groupId>junitgroupId>
    8. <artifactId>junitartifactId>
    9. <version>4.12version>
    10. <scope>testscope>
    11. dependency>
    12. <dependency>
    13. <groupId>javax.servletgroupId>
    14. <artifactId>javax.servlet-apiartifactId>
    15. <version>4.0.0version>
    16. <scope>providedscope>
    17. dependency>
    18. <dependency>
    19. <groupId>org.mybatisgroupId>
    20. <artifactId>mybatisartifactId>
    21. <version>3.4.5version>
    22. dependency>
    23. <dependency>
    24. <groupId>mysqlgroupId>
    25. <artifactId>mysql-connector-javaartifactId>
    26. <version>5.1.44version>
    27. dependency>
    28. <dependency>
    29. <groupId>org.apache.logging.log4jgroupId>
    30. <artifactId>log4j-coreartifactId>
    31. <version>2.9.1version>
    32. dependency>
    33. <dependency>
    34. <groupId>org.apache.logging.log4jgroupId>
    35. <artifactId>log4j-apiartifactId>
    36. <version>2.9.1version>
    37. dependency>
    38. <dependency>
    39. <groupId>org.apache.logging.log4jgroupId>
    40. <artifactId>log4j-webartifactId>
    41. <version>2.9.1version>
    42. dependency>
    43. dependencies>

    然后导入改变 。

    ②、将以下代码块加入finalName标签下面

    1. <resources>
    2. <resource>
    3. <directory>src/main/javadirectory>
    4. <includes>
    5. <include>**/*.xmlinclude>
    6. includes>
    7. resource>
    8. <resource>
    9. <directory>src/main/resourcesdirectory>
    10. <includes>
    11. <include>jdbc.propertiesinclude>
    12. <include>*.xmlinclude>
    13. includes>
    14. resource>
    15. resources>

     然后导入改变 。

     ③、将以下代码块加入到标签下面

    1. <plugin>
    2. <groupId>org.mybatis.generatorgroupId>
    3. <artifactId>mybatis-generator-maven-pluginartifactId>
    4. <version>1.3.2version>
    5. <dependencies>
    6. <dependency>
    7. <groupId>mysqlgroupId>
    8. <artifactId>mysql-connector-javaartifactId>
    9. <version>5.1.44version>
    10. dependency>
    11. dependencies>
    12. <configuration>
    13. <overwrite>trueoverwrite>
    14. configuration>
    15. plugin>

     然后导入改变 。

     2)导入框架的配置文件

    ①先建立一个jdbc.properties文件,然后将以下代码加入其中

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

     鼠标选中resources右键

     

     

     ②、安装插件

    Free mybatis plugin、Mybatis generator、mybatis tools、maven helper 

     

     详情介绍:Intellij Idea Mybatis 插件(plugin和tools插件)_yangshijin1988的博客-CSDN博客_idea mapper 插件

     ③修改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">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. <mapper resource="com/javaxl/mapper/BookMapper.xml"/>
    24. mappers>
    25. configuration>

     现在环境就已经搭建好了

    三、Mybatis generator插件的使用

    ①安装Mybatis generator插件

    第一步已经在上面就完成了

    ②配置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:\\Maven\\mvn_baoc\\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.mgy.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.mgy.mapper"
    24. targetProject="src/main/java">
    25. <property name="enableSubPackages" value="false"/>
    26. sqlMapGenerator>
    27. <javaClientGenerator targetPackage="com.mgy.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)、 修改jar包的路径

     2)、修改你要保存的位置

    3)、修改你要生成的表

     

    ③配置maven运行generator命令

     运行完后效果和下图一样

      

    ④、在pom中处理generatorConfig.xml不能编译问题

    步骤总结:

    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.处于性能的考虑,会采用二级缓存,二级缓存需要手动开启

    SessionUtil类:

    1. package com.mgy.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 云鹤衫
    7. * @site www.yunheshan.com
    8. * @company xxx公司
    9. * @create  2022-08-10 21:48
    10. */
    11. public class SessionUtil {
    12. private static SqlSessionFactory sessionFactory;
    13. private static ThreadLocal threadLocal = new ThreadLocal();
    14. static {
    15. sessionFactory = new SqlSessionFactoryBuilder().build(SessionUtil.class.getResourceAsStream("/mybatis.cfg.xml"));
    16. }
    17. public static SqlSession openSession() {
    18. SqlSession session = threadLocal.get();
    19. if (null == session) {
    20. session = sessionFactory.openSession();
    21. threadLocal.set(session);
    22. }
    23. return session;
    24. }
    25. public static void main(String[] args) {
    26. SqlSession session = openSession();
    27. System.out.println(session.getConnection());
    28. session.close();
    29. // System.out.println(session.getConnection());
    30. }
    31. }

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

    分析:

            有事务:增删改

            无事务:查询

    结论:

            测试:查询、删除没问题代码就没问题

    BookBiz接口:

    1. package com.mgy.biz;
    2. import com.mgy.model.Book;
    3. /**
    4. * @author 云鹤衫
    5. * @site www.yunheshan.com
    6. * @company xxx公司
    7. * @create  2022-08-10 21:59
    8. */
    9. public interface BookBiz {
    10. int deleteByPrimaryKey(Integer bid);
    11. Book selectByPrimaryKey(Integer bid);
    12. }

    BookBiz实现类:

    1. package com.mgy.biz.impl;
    2. import com.mgy.biz.BookBiz;
    3. import com.mgy.mapper.BookMapper;
    4. import com.mgy.model.Book;
    5. /**
    6. * @author 云鹤衫
    7. * @site www.yunheshan.com
    8. * @company xxx公司
    9. * @create  2022-08-10 22:03
    10. */
    11. public class BookBizImpl implements BookBiz {
    12. private BookMapper bookMapper;
    13. // alt+insert 快速提供set/get/tostring/构造方法
    14. // alt+enter 快速构建实现类,填充代码的前半部分 ctrl+1
    15. public BookMapper getBookMapper() {
    16. return bookMapper;
    17. }
    18. public void setBookMapper(BookMapper bookMapper) {
    19. this.bookMapper = bookMapper;
    20. }
    21. @Override
    22. public int deleteByPrimaryKey(Integer bid) {
    23. return bookMapper.deleteByPrimaryKey(bid);
    24. }
    25. @Override
    26. public Book selectByPrimaryKey(Integer bid) {
    27. return bookMapper.selectByPrimaryKey(bid);
    28. }
    29. }

    实现类的测试类:

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

    效果:

     项目开发中,一般会集成日志框架,日志框架的作用是帮助程序员在开发的过程中快速排除问题,定位问题;

     

  • 相关阅读:
    Blender生成COLMAP数据集
    不懂 Kubernetes 实现云原生是什么体验?
    【强化学习论文合集】IJCAI-2022 强化学习论文 | 2022年合集(五)
    Oracle创建表空间及用户
    Java之I/O
    【C++】lock_guard用法
    Python基础语法
    短视频如何展现效果更佳?不用类型的短视频有不同的侧重点
    【Vue】 Vue3 安装说明,适合小白新手
    SPDK/NVMe存储技术分析之初识UIO(二)
  • 原文地址:https://blog.csdn.net/m0_62604616/article/details/126272909