Mybatis简介
Mybatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
Mybatis是一个基于Java的持久层框架(半自动),主要包括SQL Maps和Data Access Objects(DAO)。
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。
MyBatis使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
与Hibernate的比较
Mybatis | Hibernate | |
体积 | 轻量级 | 重量级 |
自动化 | 半自动化 | 全自动化 |
支持sql | sql |
支持sql,但是推荐hql (使用sql违背了框架设计的初衷) |
扩展性 | 扩展性、迁移性比较差 |
无缝移植(方言) |
准备环境
创建工程并且添加pom依赖(包括mybatis、mysql、junit、servlet、log4j2),更改为1.8:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.star</groupId> <artifactId>ssm_01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm_01 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.13</junit.version> <servlet.version>4.0.1</servlet.version> <mybatis.version>3.4.5</mybatis.version> <mysql.version>5.1.44</mysql.version> </properties> <dependencies> <!-- ********************** junit单元测试依赖 ********************** --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- ********************** Java Servlet API ********************** --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <!-- ********************** Mybatis依赖 ********************** --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- ********************** Mysql JDBC驱动 ********************** --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- ********************** 日志配置 ********************** --> <!--记得修改mybatis.cfg.xml添加如下内容--> <!--<setting name="logImpl" value="LOG4J2"/>--> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.9.1</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.9.1</version> </dependency> </dependencies> <build> <finalName>ssm_01</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
添加web支持:
<!--第一步就是配置maven-compiler-plugin插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 修改web.xml由2.3至3.0 --> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- web项目还需要修改web.xml文件添加日志开关,禁止自动初始化log4j2 --> <context-param> <param-name>isLog4jAutoInitializationDisabled</param-name> <param-value>false</param-value> </context-param>
添加配置文件
jdbc.properties文件(更改密码和数据库):
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false jdbc.username=root jdbc.password=123456
log4j2配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. --> <Configuration status="WARN" monitorInterval="30"> <Properties> <!-- 配置日志文件输出目录 ${sys:user.home} --> <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property> <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property> <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property> <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property> </Properties> <Appenders> <!--这个输出控制台的配置 --> <Console name="Console" target="SYSTEM_OUT"> <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" /> <!-- 输出日志的格式 --> <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称 %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 --> <PatternLayout pattern="${PATTERN}" /> </Console> <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 --> <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true --> <File name="log" fileName="logs/test.log" append="false"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </File> <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 --> <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) --> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. --> <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 --> <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. --> <!-- <SizeBasedTriggeringPolicy size="2 kB" /> --> </Policies> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log" filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="2 kB" /> </Policies> <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 --> <DefaultRolloverStrategy max="20" /> </RollingFile> <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log" filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log --> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> <!-- <SizeBasedTriggeringPolicy size="10 MB" /> --> </Policies> </RollingFile> </Appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 --> <Loggers> <!--过滤掉spring和mybatis的一些无用的DEBUG信息 --> <logger name="org.springframework" level="INFO"></logger> <logger name="org.mybatis" level="INFO"></logger> <!-- 第三方日志系统 --> <logger name="org.springframework" level="ERROR" /> <logger name="org.hibernate" level="ERROR" /> <logger name="org.apache.struts2" level="ERROR" /> <logger name="com.opensymphony.xwork2" level="ERROR" /> <logger name="org.jboss" level="ERROR" /> <!-- 配置日志的根节点 --> <root level="all"> <appender-ref ref="Console" /> <appender-ref ref="RollingFileInfo" /> <appender-ref ref="RollingFileWarn" /> <appender-ref ref="RollingFileError" /> </root> </Loggers> </Configuration>
mybatis.cfg,xml文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 1.引入外部数据库配置文件 2.配置日志输出文件为log4j2 3.别名配置 4.mybatis的运行环境(定义事务管理和连接池) 5.配置sql映射文件并且包含在此 --> <!-- 引入外部配置文件 --> <properties resource="jdbc.properties"/> <!-- 初始化配置 --> <settings> <setting name="logImpl" value="LOG4J2"/> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 别名,就是要注册的类 --> <typeAliases> <!-- <typeAlias type="com.zking.oa.model.Book" alias="Book"/>--> <!--<package name="com.star.mapper"/>--> </typeAliases> <!-- 配置mybatis运行环境 --> <environments default="development"> <environment id="development"> <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 --> <transactionManager type="jdbc"/> <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI --> <!-- POOLED 表示支持JDBC数据源连接池 --> <!-- UNPOOLED 表示不支持数据源连接池 --> <!-- JNDI 表示支持外部数据源连接池 --> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 在此处添加自己的mapper映射 --> <!-- <mappers> <mapper resource="com/zking/oa/mapper/BookMapper.xml"/> </mappers>--> </configuration>
运行工具类MybatisSessionFactoryUtils进行测试:
package com.star.mapper.util; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MybatisSessionFactoryUtils { public static SqlSessionFactory sqlSessionFactory; private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>(); static { try { InputStream is = MybatisSessionFactoryUtils.class .getResourceAsStream("/mybatis.cfg.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); sqlSessionFactory = sqlSessionFactoryBuilder.build(is); } catch (Exception e) { throw new RuntimeException(e); } } private MybatisSessionFactoryUtils() { } public static SqlSession openSession() { SqlSession sqlSession = threadLocal.get(); if (null == sqlSession) { sqlSession = sqlSessionFactory.openSession(); threadLocal.set(sqlSession); } return sqlSession; } public static void closeSession() { SqlSession sqlSession = threadLocal.get(); if (null != sqlSession) { threadLocal.set(null); sqlSession.close(); } } public static void main(String[] args) { SqlSession sqlSession = MybatisSessionFactoryUtils.openSession(); System.out.println(sqlSession); System.out.println(sqlSession.getConnection()); MybatisSessionFactoryUtils.closeSession(); } }
成功如下:
至此就完成了Mybatis的环境配置。
生成代码
在IDEA中使用MyBatis-generator插件自动生成MyBatis代码
比如:Xxx.java、XxxMapper.java、XxxMapper.xml
首先下载插件,然后导入插件依赖,这是导入后的pom.xml(注意自己的项目名):
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.star</groupId> <artifactId>ssm_01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm_01 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>4.13</junit.version> <servlet.version>4.0.1</servlet.version> <mybatis.version>3.4.5</mybatis.version> <mysql.version>5.1.44</mysql.version> </properties> <dependencies> <!-- ********************** junit单元测试依赖 ********************** --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- ********************** Java Servlet API ********************** --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <!-- ********************** Mybatis依赖 ********************** --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- ********************** Mysql JDBC驱动 ********************** --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- ********************** lombok插件 ********************** --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> <scope>provided</scope> </dependency> <!-- ********************** 日志配置 ********************** --> <!--记得修改mybatis.cfg.xml添加如下内容--> <!--<setting name="logImpl" value="LOG4J2"/>--> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.9.1</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.9.1</version> </dependency> </dependencies> <build> <finalName>ssm_01</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> </plugins> </build> </project>
准备generatorConfig.xml文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="jdbc.properties"/> <!--指定数据库jdbc驱动jar包的位置--> <classPathEntry location="D:/softWare/repository/mvn_repository/mysql/mysql-connector-java/5.1.44/mysql-connector-java-5.1.44.jar"/> <!-- 一个数据库一个context --> <context id="infoGuardian"> <!-- 注释 --> <commentGenerator> <property name="suppressAllComments" value="true"/><!-- 是否取消注释 --> <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 --> </commentGenerator> <!-- jdbc连接 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <!-- 类型转换 --> <javaTypeResolver> <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) --> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 01 指定javaBean生成的位置 --> <!-- targetPackage:指定生成的model生成所在的包名 --> <!-- targetProject:指定在该项目下所在的路径 --> <javaModelGenerator targetPackage="com.star.model" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="true"/> <!-- 是否对model添加构造函数 --> <property name="constructorBased" value="true"/> <!-- 是否针对string类型的字段在set的时候进行trim调用 --> <property name="trimStrings" value="false"/> <!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 --> <property name="immutable" value="false"/> </javaModelGenerator> <!-- 02 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.star.mapper" targetProject="src/main/java"> <!-- 是否允许子包,即targetPackage.schemaName.tableName --> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 03 生成XxxMapper接口 --> <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 --> <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 --> <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 --> <javaClientGenerator targetPackage="com.star.mapper" targetProject="src/main/java" type="XMLMAPPER"> <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] --> <property name="enableSubPackages" value="false"/> </javaClientGenerator> <!-- 配置表信息 --> <!-- schema即为数据库名 --> <!-- tableName为对应的数据库表 --> <!-- domainObjectName是要生成的实体类 --> <!-- enable*ByExample是否生成 example类 --> <!--<table schema="" tableName="t_book" domainObjectName="Book"--> <!--enableCountByExample="false" enableDeleteByExample="false"--> <!--enableSelectByExample="false" enableUpdateByExample="false">--> <!--<!– 忽略列,不生成bean 字段 –>--> <!--<!– <ignoreColumn column="FRED" /> –>--> <!--<!– 指定列的java数据类型 –>--> <!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>--> <!--</table>--> <table schema="" tableName="t_book_vue" domainObjectName="Book" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> <!-- 忽略列,不生成bean 字段 --> <!-- <ignoreColumn column="FRED" /> --> <!-- 指定列的java数据类型 --> <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> --> </table> </context> </generatorConfiguration>
然后配置一个插件生成启动配置:
然后配置如下:
我在这里出现过一次错误:generator Column name pattern can not be NULL or empty
此错误是由于mysql驱动版本过高引起的,可以参考这篇博客解决。
配置好以后启动,成功如下:
CRUD案例
实体类用了lombok插件(要导入依赖):
package com.star.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Book { private Integer id; private String bookname; private Float price; private String booktype; }
直接就用生成的mapper层:
package com.star.mapper; import com.star.model.Book; import java.util.List; public interface BookMapper { int deleteByPrimaryKey(Integer id); List<Book> queryBookPager(Book bk); int insert(Book record); int insertSelective(Book record); Book selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Book record); int updateByPrimaryKey(Book record); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.star.mapper.BookMapper" > <resultMap id="BaseResultMap" type="com.star.model.Book" > <constructor > <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <arg column="bookname" jdbcType="VARCHAR" javaType="java.lang.String" /> <arg column="price" jdbcType="REAL" javaType="java.lang.Float" /> <arg column="booktype" jdbcType="VARCHAR" javaType="java.lang.String" /> </constructor> </resultMap> <sql id="Base_Column_List" > id, bookname, price, booktype </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from t_book_vue where id = #{id,jdbcType=INTEGER} </select> <select id="queryBookPager" resultType="com.star.model.Book"> select <include refid="Base_Column_List"/> from t_book_vue order by id desc </select> <delete id="deleteByPrimaryKey" parameterType="integer" > delete from t_book_vue where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.star.model.Book" > insert into t_book_vue (bookname, price,booktype) values (#{bookname,jdbcType=VARCHAR}, #{price,jdbcType=REAL},#{booktype,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.star.model.Book" > insert into t_book_vue <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="bookname != null" > bookname, </if> <if test="price != null" > price, </if> <if test="booktype != null" > booktype, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="bookname != null" > #{bookname,jdbcType=VARCHAR}, </if> <if test="price != null" > #{price,jdbcType=REAL}, </if> <if test="booktype != null" > #{booktype,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.star.model.Book" > update t_book_vue <set > <if test="bookname != null" > bookname = #{bookname,jdbcType=VARCHAR}, </if> <if test="price != null" > price = #{price,jdbcType=REAL}, </if> <if test="booktype != null" > booktype = #{booktype,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.star.model.Book" > update t_book_vue set bookname = #{bookname,jdbcType=VARCHAR}, price = #{price,jdbcType=REAL}, booktype = #{booktype,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>
准备service层接口和实现:
package com.star.service; import com.star.model.Book; import java.util.List; public interface IBookService { /** * 删除单个 * @param id 主键 * @return 影响行数 */ int deleteByPrimaryKey(Integer id); /** * 分页查询 * @param bk 对象 * @return 集合 */ List<Book> queryBookPager(Book bk); /** * 增加操作 * @param record 对象 * @return 影响行数 */ int insert(Book record); /** * 查询单个 * @param id 主键 * @return 影响行数 */ Book selectByPrimaryKey(Integer id); /** * 更新操作 * @param record 对象 * @return 影响行数 */ int updateByPrimaryKey(Book record); }
package com.star.service.serviceImpl; import com.star.mapper.BookMapper; import com.star.model.Book; import com.star.service.IBookService; import java.util.List; public class BookServiceImpl implements IBookService { private BookMapper bookMapper; public BookMapper getBookMapper() { return bookMapper; } public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int deleteByPrimaryKey(Integer id) { return bookMapper.deleteByPrimaryKey(id); } @Override public List<Book> queryBookPager(Book bk) { return bookMapper.queryBookPager(bk); } @Override public int insert(Book record) { return bookMapper.insert(record); } @Override public Book selectByPrimaryKey(Integer id) { return bookMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKey(Book record) { return bookMapper.updateByPrimaryKey(record); } }
准备测试类:
package com.star.service.serviceImpl; import com.star.mapper.BookMapper; import com.star.model.Book; import com.star.service.IBookService; import com.star.util.MybatisSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class BookServiceImplTest { private IBookService bookService; private SqlSession sqlSession; public SqlSession getSqlSession() { return sqlSession; } public void setSqlSession(SqlSession sqlSession) { this.sqlSession = sqlSession; } private Book book; public IBookService getBookService() { return bookService; } public void setBookService(IBookService bookService) { this.bookService = bookService; } @Before public void setUp() throws Exception { sqlSession = MybatisSessionFactoryUtils.openSession(); BookMapper mapper = sqlSession.getMapper(BookMapper.class); bookService = new BookServiceImpl(); ((BookServiceImpl) bookService).setBookMapper(mapper); } @After public void tearDown() throws Exception { sqlSession.commit(); MybatisSessionFactoryUtils.closeSession(); } @Test public void deleteByPrimaryKey() { int n = bookService.deleteByPrimaryKey(2); if(n>0) System.out.println("成功"); } @Test public void queryBookPager() { List<Book> list =bookService.queryBookPager(new Book()); list.forEach(System.out::println); } @Test public void insert() { int n = bookService.insert(Book.builder().bookname("你好啊").price(321f).booktype("1-1").build()); if(n>0) System.out.println("成功!"); } @Test public void selectByPrimaryKey() { Book n =bookService.selectByPrimaryKey(6); System.out.println(n); } @Test public void updateByPrimaryKey() { int n = bookService.updateByPrimaryKey(Book.builder().bookname("n颠三倒四").booktype("1-2").price(123f).id(2).build()); if(n>0) System.out.println("成功"); } }
测试成功数据库新增成功了。