搭建mybatis框架环境
1、创建maven工程
2、导入相关pom依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.MavenMybatis</groupId> 8 <artifactId>Mybatis_1</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>Mybatis_1 Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <maven.compiler.source>1.8</maven.compiler.source> 18 <maven.compiler.target>1.8</maven.compiler.target> 19 </properties> 20 21 22 <dependencies> 23 <!-- ********************** junit单元测试依赖 ********************** --> 24 <dependency> 25 <groupId>junit</groupId> 26 <artifactId>junit</artifactId> 27 <version>4.12</version> 28 <scope>test</scope> 29 </dependency> 30 31 <!-- ********************** Java Servlet API ********************** --> 32 <dependency> 33 <groupId>javax.servlet</groupId> 34 <artifactId>javax.servlet-api</artifactId> 35 <version>4.0.0</version> 36 <scope>provided</scope> 37 </dependency> 38 39 <!-- ********************** Mybatis依赖 ********************** --> 40 <dependency> 41 <groupId>org.mybatis</groupId> 42 <artifactId>mybatis</artifactId> 43 <version>3.4.5</version> 44 </dependency> 45 46 <!-- ********************** Mysql JDBC驱动 ********************** --> 47 <dependency> 48 <groupId>mysql</groupId> 49 <artifactId>mysql-connector-java</artifactId> 50 <version>5.1.44</version> 51 </dependency> 52 53 <!-- ********************** 日志配置 ********************** --> 54 <!--记得修改mybatis.cfg.xml添加如下内容--> 55 <!--<setting name="logImpl" value="LOG4J2"/>--> 56 <!--核心log4j2jar包--> 57 <dependency> 58 <groupId>org.apache.logging.log4j</groupId> 59 <artifactId>log4j-core</artifactId> 60 <version>2.9.1</version> 61 </dependency> 62 <dependency> 63 <groupId>org.apache.logging.log4j</groupId> 64 <artifactId>log4j-api</artifactId> 65 <version>2.9.1</version> 66 </dependency> 67 <!--web工程需要包含log4j-web,非web工程不需要--> 68 <dependency> 69 <groupId>org.apache.logging.log4j</groupId> 70 <artifactId>log4j-web</artifactId> 71 <version>2.9.1</version> 72 </dependency> 73 </dependencies> 74 75 <build> 76 <finalName>Mybatis_1</finalName> 77 <resources> 78 <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> 79 <resource> 80 <directory>src/main/java</directory> 81 <includes> 82 <include>**/*.xml</include> 83 </includes> 84 </resource> 85 <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> 86 <resource> 87 <directory>src/main/resources</directory> 88 <includes> 89 <include>jdbc.properties</include> 90 <include>*.xml</include> 91 </includes> 92 </resource> 93 </resources> 94 95 <plugins> 96 <plugin> 97 <groupId>org.mybatis.generator</groupId> 98 <artifactId>mybatis-generator-maven-plugin</artifactId> 99 <version>1.3.2</version> 100 <dependencies> 101 <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> 102 <dependency> 103 <groupId>mysql</groupId> 104 <artifactId>mysql-connector-java</artifactId> 105 <version>5.1.44</version> 106 </dependency> 107 </dependencies> 108 <configuration> 109 <overwrite>true</overwrite> 110 </configuration> 111 </plugin> 112 </plugins> 113 </build> 114 </project>
Jdbc.properties
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/xufanqi?useUnicode=true&characterEncoding=UTF-8 3 jdbc.username=root 4 jdbc.password=123
Web.xml
1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 2 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 5 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 6 7 version="3.1"></web-app>
3、Mybatis相关插件安装
Free mybatis plugin
Mybatis generator
mybatis tools
maven helper
4、Mybatis.cfg.xml配置
Mybatis.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 <configuration> 4 <!-- 引入外部配置文件 --> 5 <properties resource="jdbc.properties"/> 6 7 <settings> 8 <setting name="logImpl" value="LOG4J2"/> 9 </settings> 10 11 <!-- 别名 --> 12 <typeAliases> 13 <!--<typeAlias type="com.javaxl.model.Book" alias="Book"/>--> 14 </typeAliases> 15 16 17 <!-- 配置mybatis运行环境 --> 18 <environments default="development"> 19 <environment id="development"> 20 <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 --> 21 <transactionManager type="jdbc"/> 22 23 <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI --> 24 <!-- POOLED 表示支持JDBC数据源连接池 --> 25 <!-- UNPOOLED 表示不支持数据源连接池 --> 26 <!-- JNDI 表示支持外部数据源连接池 --> 27 <dataSource type="POOLED"> 28 <property name="driver" 29 value="${jdbc.driver}"/> 30 <property name="url" 31 value="${jdbc.url}"/> 32 <property name="username" value="${jdbc.username}"/> 33 <property name="password" value="${jdbc.password}"/> 34 </dataSource> 35 </environment> 36 </environments> 37 38 <mappers> 39 <mapper resource="com/Mybatis/mapper/BookMapper.xml"/> 40 </mappers> 41 </configuration>
基于ssm逆向工程的使用
1、配置generatorConfig.xml
更改<!--指定数据库jdbc驱动jar包的位置-->
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 3 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > 4 <generatorConfiguration> 5 <!-- 引入配置文件 --> 6 <properties resource="jdbc.properties"/> 7 8 <!--指定数据库jdbc驱动jar包的位置--> 9 <classPathEntry location="D:\apache-maven-3.5.0-bin\apache-maven-3.5.0-bin\Mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/> 10 11 <!-- 一个数据库一个context --> 12 <context id="infoGuardian"> 13 <!-- 注释 --> 14 <commentGenerator> 15 <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> 16 <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> 17 </commentGenerator> 18 19 <!-- jdbc连接 --> 20 <jdbcConnection driverClass="${jdbc.driver}" 21 connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> 22 23 <!-- 类型转换 --> 24 <javaTypeResolver> 25 <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> 26 <property name="forceBigDecimals" value="false"/> 27 </javaTypeResolver> 28 29 <!-- 01 指定javaBean生成的位置 --> 30 <!-- targetPackage:指定生成的model生成所在的包名 --> 31 <!-- targetProject:指定在该项目下所在的路径 --> 32 <javaModelGenerator targetPackage="com.Mybatis.model" 33 targetProject="src/main/java"> 34 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 35 <property name="enableSubPackages" value="false"/> 36 <!-- 是否对model添加构造函数 --> 37 <property name="constructorBased" value="true"/> 38 <!-- 是否针对string类型的字段在set的时候进行trim调用 --> 39 <property name="trimStrings" value="false"/> 40 <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> 41 <property name="immutable" value="false"/> 42 </javaModelGenerator> 43 44 <!-- 02 指定sql映射文件生成的位置 --> 45 <sqlMapGenerator targetPackage="com.Mybatis.mapper" 46 targetProject="src/main/java"> 47 <!-- 是否允许子包,即targetPackage.schemaName.tableName --> 48 <property name="enableSubPackages" value="false"/> 49 </sqlMapGenerator> 50 51 <!-- 03 生成XxxMapper接口 --> 52 <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> 53 <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> 54 <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> 55 <javaClientGenerator targetPackage="com.Mybatis.mapper" 56 targetProject="src/main/java" type="XMLMAPPER"> 57 <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> 58 <property name="enableSubPackages" value="false"/> 59 </javaClientGenerator> 60 61 <!-- 配置表信息 --> 62 <!-- schema即为数据库名 --> 63 <!-- tableName为对应的数据库表 --> 64 <!-- domainObjectName是要生成的实体类 --> 65 <!-- enable*ByExample是否生成 example类 --> 66 <!--<table schema="" tableName="t_book" domainObjectName="Book"--> 67 <!--enableCountByExample="false" enableDeleteByExample="false"--> 68 <!--enableSelectByExample="false" enableUpdateByExample="false">--> 69 <!--<!– 忽略列,不生成bean 字段 –>--> 70 <!--<!– <ignoreColumn column="FRED" /> –>--> 71 <!--<!– 指定列的java数据类型 –>--> 72 <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> 73 <!--</table>--> 74 75 <table schema="" tableName="t_mvc_Book" domainObjectName="Book" 76 enableCountByExample="false" enableDeleteByExample="false" 77 enableSelectByExample="false" enableUpdateByExample="false"> 78 <!-- 忽略列,不生成bean 字段 --> 79 <!-- <ignoreColumn column="FRED" /> --> 80 <!-- 指定列的java数据类型 --> 81 <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> 82 </table> 83 84 </context> 85 </generatorConfiguration>
配置maven运行generator命令
Mybatis增删改查案例
SessionUtil
1 package com.Mybatis.util; 2 3 import org.apache.ibatis.session.SqlSession; 4 import org.apache.ibatis.session.SqlSessionFactory; 5 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 6 7 8 public class SessionUtil { 9 private static SqlSessionFactory sessionFactory; 10 private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); 11 static { 12 sessionFactory = new SqlSessionFactoryBuilder().build(SessionUtil.class.getResourceAsStream("/mybatis.cfg.xml")); 13 } 14 15 public static SqlSession openSession() { 16 SqlSession session = threadLocal.get(); 17 if (null == session) { 18 session = sessionFactory.openSession(); 19 threadLocal.set(session); 20 } 21 return session; 22 } 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 }
BookService
1 package com.Mybatis.service; 2 3 import com.Mybatis.model.Book; 4 5 public interface BookService { 6 7 int deleteByPrimaryKey(Integer bid); 8 9 int insert(Book record); 10 11 12 int insertSelective(Book record); 13 }
新建BookService,将BookMapper复制到BookService,选中类名BookService,Alt+回车生成实现类BookServiceImpl
BookServiceImpl
1 package com.Mybatis.service.impl; 2 3 import com.Mybatis.mapper.BookMapper; 4 import com.Mybatis.model.Book; 5 import com.Mybatis.service.BookService; 6 7 public class BookServiceImpl implements BookService { 8 public BookMapper getBookMapper() { 9 return bookMapper; 10 } 11 12 public void setBookMapper(BookMapper bookMapper) { 13 this.bookMapper = bookMapper; 14 } 15 16 private BookMapper bookMapper; 17 18 19 20 21 22 @Override 23 public int deleteByPrimaryKey(Integer bid) { 24 return bookMapper.deleteByPrimaryKey(bid); 25 } 26 27 @Override 28 public int insert(Book record) { 29 return bookMapper.insert(record); 30 } 31 32 @Override 33 public int insertSelective(Book record) { 34 return bookMapper.insertSelective(record); 35 } 36 }
测试
BookServiceTest
1 package com.Mybatis.service; 2 3 4 import com.Mybatis.mapper.BookMapper; 5 import com.Mybatis.model.Book; 6 import com.Mybatis.service.impl.BookServiceImpl; 7 import com.Mybatis.util.SessionUtil; 8 import org.apache.ibatis.session.SqlSession; 9 import org.junit.After; 10 import org.junit.Before; 11 import org.junit.Test; 12 13 public class BookServiceTest { 14 15 private BookService bookService; 16 private SqlSession sqlSession; 17 @Before 18 public void setUp(){ 19 BookServiceImpl bookService = new BookServiceImpl(); 20 sqlSession = SessionUtil.openSession(); 21 BookMapper mapper = sqlSession.getMapper(BookMapper.class); 22 bookService.setBookMapper(mapper); 23 this.bookService = bookService; 24 } 25 26 @Test 27 public void deleteByPrimaryKey() { 28 29 } 30 31 @Test 32 public void insert() { 33 Book book = new Book(); 34 book.setBid(1); 35 book.setBname("Mybatis插入"); 36 book.setPrice(22); 37 bookService.insert(book); 38 } 39 40 @Test 41 public void insertSelective() { 42 } 43 44 @After 45 public void tearDown() throws Exception{ 46 sqlSession.commit(); 47 sqlSession.close(); 48 } 49 }
新增