• mybatis入门


    目录

    一、搭建mybatis框架环境

    二、基于ssm逆向工程的使用(IDEA)

    三、Mybatis增删改查案例


     前言:什么是Mybatis

    它是一款半自动的ORM持久层框架,具有较高的SQL灵活性,支持高级映射(一对一,一对多),动态SQL,延迟加载和缓存等特性,但它的数据库无关性较低它是一款半自动的ORM持久层框架,具有较高的SQL灵活性,支持高级映射(一对一,一对多),动态SQL,延迟加载和缓存等特性,但它的数据库无关性较低


    一、搭建mybatis框架环境

            1、创建maven工程

    首先我们在学习mybatis之前先创建一个基础的maven项目 

            右击项目名——>new——>module

             选择maven项目——>选择jdk版本——>选择webapp

             输入项目名

             选择好maven项目的文件位置——>点击添加按钮——>配置好参数

             2、导入相关pom依赖

    创建好maven项目之后我们还需修改一下,我们可以去看一下小编的另外一篇文章,我们可以修改一下在这里小编就不在重复写了。接下来我们导入Mybatis 的相关pom依赖

    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>
    44. <build>
    45. <resources>
    46. <resource>
    47. <directory>src/main/javadirectory>
    48. <includes>
    49. <include>**/*.xmlinclude>
    50. includes>
    51. resource>
    52. <resource>
    53. <directory>src/main/resourcesdirectory>
    54. <includes>
    55. <include>jdbc.propertiesinclude>
    56. <include>*.xmlinclude>
    57. includes>
    58. resource>
    59. resources>
    60. <plugins>
    61. <plugin>
    62. <groupId>org.mybatis.generatorgroupId>
    63. <artifactId>mybatis-generator-maven-pluginartifactId>
    64. <version>1.3.2version>
    65. <dependencies>
    66. <dependency>
    67. <groupId>mysqlgroupId>
    68. <artifactId>mysql-connector-javaartifactId>
    69. <version>5.1.44version>
    70. dependency>
    71. dependencies>
    72. <configuration>
    73. <overwrite>trueoverwrite>
    74. configuration>
    75. plugin>
    76. plugins>
    77. build>

            然后我们知道Mybatis是一款有关于数据库的框架,所以我们还需要导入关于数据库连接的配置文件:

      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

    修改web.xml文件

    1. web-app PUBLIC
    2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
    4. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    7. version="3.1">web-app>

            3、Mybatis相关插件安装

            配置好pom依赖之后我们继续学习mybatis的环境搭建,接下来我们需要安装几款插件

    ①        Free mybatis plugin

    ②        Mybatis generator

    ③        mybatis tools

    ④        maven helper 

              4、Mybatis.cfg.xml配置

    众所周知,一款框架必定有自己的配置文件,Mybatis也是一样有配置文件

    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>

    二、基于ssm逆向工程的使用(IDEA)

            1、安装Mybatis generator插件

    这个插件我们刚才已经安装好了

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

      1.2 修改实体类生成的地址

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

      1.4修改Dao层代码地址

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

            3、配置maven运行generator命令

     我们再在pom文件中右键

     然后我们就可以看到它将帮我们自定创建好了实体类和方法了


    三、Mybatis增删改查案例

    插叙:面试题:SQLSession的作用

    sqlsession的作用:

    1.sqlsession可以拿到mapper对象

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

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

        创建一个util包和一个SessionUtil

    1. package com.zq.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.zq.com
    8. * @create  2022-08-11 1:32
    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. }
    29. }

     创建biz层BookBiz:

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

    bookbizimpl实现bookbiz

    1. package com.zq.biz.impl;
    2. import com.zq.biz.BookBiz;
    3. import com.zq.mapper.BookMapper;
    4. import com.zq.model.Book;
    5. /**
    6. * @author张强
    7. * @site www.zq.com
    8. * @create  2022-08-11 1:38
    9. */
    10. public class BookBizImpl implements BookBiz {
    11. private BookMapper bookMapper;
    12. public BookMapper getBookMapper() {
    13. return bookMapper;
    14. }
    15. public void setBookMapper(BookMapper bookMapper) {
    16. this.bookMapper = bookMapper;
    17. }
    18. @Override
    19. public int deleteByPrimaryKey(Integer bid) {
    20. return bookMapper.deleteByPrimaryKey(bid);
    21. }
    22. @Override
    23. public Book selectByPrimaryKey(Integer bid) {
    24. return bookMapper.selectByPrimaryKey(bid);
    25. }
    26. }

    以及它的测试类BookBizImplTest

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

  • 相关阅读:
    C++ 单向链表手动实现(课后作业版)
    Centos7 升级 Kubernetes(k8s) 集群
    微信支付证V3
    html:mate
    jQuery中attr()、prop()、data()用法及区别
    java计算机毕业设计基于springboo+vue的旅游自驾游攻略方案分享系统
    java计算机毕业设计中小型超市管理系统源程序+mysql+系统+lw文档+远程调试
    c++|引用
    CSS3 简介
    《MLB棒球创造营》:走近棒球运动·西雅图水手队
  • 原文地址:https://blog.csdn.net/weixin_66110079/article/details/126276724