MyBatis 是一款優(yōu)秀的持久層框架发框,它支持定制化 SQL躺彬、存儲過程以及高級映射煤墙。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集梅惯。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數(shù)據(jù)庫中的記錄仿野。
本節(jié)實(shí)例采用封裝的Mybatis通用Mapper和Spring整合铣减,演示基本的單表CRUD,復(fù)雜的SQL建議自定義
tk-mybatis地址: https://github.com/abel533/Mapper
1脚作、首先建立數(shù)據(jù)庫 庫名db_spring 表名t_user
2葫哗、orm模塊結(jié)構(gòu)
3、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.spring.orm</groupId>
<artifactId>ORM</artifactId>
<version>1.0-SNAPSHOT</version>
<name>ORM</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>
<spring.version>5.1.5.RELEASE</spring.version>
<aspectj.version>1.9.2</aspectj.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.12</slf4j.version>
<hutool.version>4.5.1</hutool.version>
<mysql.version>5.1.47</mysql.version>
<mybatis.version>3.5.0</mybatis.version>
<mybatis-spring.version>2.0.0</mybatis-spring.version>
<tk-mybatis.version>4.1.5</tk-mybatis.version>
<druid.version>1.1.14</druid.version>
<lombok.version>1.18.6</lombok.version>
</properties>
<dependencies>
<!--junit依賴-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-test依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-aop依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--aspectj依賴-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<!--Lombok 依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- log4j日志依賴 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<!--hutool依賴-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-jdbc依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mysql依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mybatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis-spring依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!--通用mapper依賴-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk-mybatis.version}</version>
</dependency>
<!--druid依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_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-jar-plugin</artifactId>
<version>3.0.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>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
- jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
- log4j.properties
##日志輸出的級別球涛,以及配置記錄方案
log4j.rootLogger=debug, stdout,file
##設(shè)置日志記錄到控制臺的方式
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
##設(shè)置日志記錄到文件的方式
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logs/my_log.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
- spring_mybatis.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--讀入外部數(shù)據(jù)庫連接屬性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--掃描Service包的組件-->
<context:component-scan base-package="com.spring.orm.service"/>
<!--通過druid配置數(shù)據(jù)源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 初始化大小 -->
<property name="initialSize" value="20"/>
<!-- 連接池最大使用連接數(shù)量 -->
<property name="maxActive" value="20"/>
<!-- 連接池最小空閑 -->
<property name="minIdle" value="0"/>
<!-- 配置獲取連接等待超時(shí)的時(shí)間 -->
<property name="maxWait" value="60000"/>
<!-- 配置間隔多久才進(jìn)行一次檢測劣针,檢測需要關(guān)閉的空閑連接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一個(gè)連接在池中最小生存的時(shí)間亿扁,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<!-- 連接空閑時(shí)測試是否有效 -->
<property name="testWhileIdle" value="false"/>
<!-- 獲取連接時(shí)測試是否有效 -->
<property name="testOnBorrow" value="false"/>
<!-- 歸還連接時(shí)是否測試有效 -->
<property name="testOnReturn" value="false"/>
<!-- 打開PSCache緩存捺典,并且指定每個(gè)連接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
</bean>
<!-- 配置mybatis的Session -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.spring.orm.entity"/>
</bean>
<!-- 配置通用Mapper -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.spring.orm.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="markerInterface" value="com.spring.orm.dao.BaseDAO"/>
<property name="properties">
<value>
mappers = com.spring.orm.dao.BaseDAO
IDENTITY = MYSQL
</value>
</property>
</bean>
<!--事務(wù)管理bean -->
<bean id="manager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 使用聲明式事務(wù) -->
<tx:annotation-driven transaction-manager="manager"/>
</beans>
- User類
package com.spring.orm.entity;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "t_user")
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String account;
private String password;
private Integer credits;
}
- BaseDAO接口
package com.spring.orm.dao;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
/**
* 通用DAO接口
*/
public interface BaseDAO<T> extends Mapper<T>, MySqlMapper<T> {
}
- UserDAO接口
package com.spring.orm.dao;
import com.spring.orm.entity.User;
/**
* UserDAO,繼承通用DAO接口基礎(chǔ)的CRUD功能
*/
public interface UserDAO extends BaseDAO<User> {
}
- UserService接口
package com.spring.orm.service;
import com.spring.orm.entity.User;
import java.util.List;
public interface UserService {
/**
* 新增用戶
*
* @param user
* @return
*/
int insertUser(User user);
/**
* 根據(jù)id刪除用戶
*
* @param id
* @return
*/
int deleteUser(long id);
/**
* 更新用戶
*
* @param user
* @return
*/
int updateUser(User user);
/**
* 查詢所有用戶
*
* @return
*/
List<User> selectUsers();
/**
* 根據(jù)id查詢用戶
*
* @param id
* @return
*/
User getUser(long id);
}
- UserServiceImpl實(shí)現(xiàn)類
package com.spring.orm.service.impl;
import com.spring.orm.dao.UserDAO;
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public int insertUser(User user) {
return userDAO.insert(user);
}
@Override
public int deleteUser(long id) {
return userDAO.deleteByPrimaryKey(id);
}
@Override
public int updateUser(User user) {
return userDAO.updateByPrimaryKey(user);
}
@Override
public List<User> selectUsers() {
return userDAO.selectAll();
}
@Override
public User getUser(long id) {
return userDAO.selectByPrimaryKey(id);
}
}
- 對UserServiceImpl進(jìn)行單元測試
package com.spring.orm.service.Impl;
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring_mybatis.xml"})
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void insertUser() {
User user = new User();
user.setAccount("test");
user.setPassword("89898");
user.setCredits(8955);
int n = userService.insertUser(user);
assertEquals(1, n);
}
@Test
public void deleteUser() {
int n = userService.deleteUser(10);
assertEquals(1,n);
}
@Test
public void updateUser() {
User user = userService.getUser(12);
user.setPassword("00000000");
user.setCredits(1111111);
int n = userService.updateUser(user);
assertEquals(1, n);
}
@Test
public void selectUsers() {
List<User> users = userService.selectUsers();
users.forEach(user -> System.out.println(user));
}
@Test
public void getUser() {
User user = userService.getUser(1);
System.out.println(user);
}
}