Spring整合MyBatis
Author:Exchanges
Version:9.0.2
目录
Spring整合MyBatis
1. 创建 t_user 表并添加数据
create table t_user(
id int primary key auto_increment,
name varchar(50),
password varchar(50)
)default charset = utf8;
INSERT INTO t_user(NAME,PASSWORD) VALUES("jack","123");
INSERT INTO t_user(NAME,PASSWORD) VALUES("tom","456");
INSERT INTO t_user(NAME,PASSWORD) VALUES("rose","789");
2. pom.xml导入相关依赖
<dependencies>
<!-- mybatis相关 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- spring相关 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.20</version>
</dependency>
<!-- mybatis整合spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
3. 编写pojo
package com.qf.pojo;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String password;
}
4. 创建 UserController
package com.qf.controller;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.util.List;
@Controller
public class UserController {
@Autowired
public UserService userService;
public List<User> findAll(){
return userService.findAll();
}
}
5. 创建 UserService
package com.qf.service;
import com.qf.pojo.User;
import java.util.List;
public interface UserService {
List<User> findAll();
}
6. 创建UserServiceImpl
package com.qf.service.impl;
import com.qf.mapper.UserMapper;
import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}
7. 创建UserMapper
package com.qf.mapper;
import com.qf.pojo.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
List<User> findAll();
}
8. 创建mapper目录,然后再创建UserMapper.xml
<?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.qf.mapper.UserMapper">
<resultMap id="userMap" type="com.qf.pojo.User">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="password" column="password"></result>
</resultMap>
<sql id="baseSql">
select id,name,password from t_user
</sql>
<select id="findAll" resultMap="userMap">
<include refid="baseSql"></include>
</select>
</mapper>
9. 创建 db.properties
db.username = root
db.password = root
db.url = jdbc:mysql://localhost:3306/java2203?serverTimezone=Asia/Shanghai&characterEncoding=UTF8
db.driver = com.mysql.cj.jdbc.Driver
10. 创建log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
11. 创建mybatis-config.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>
<!-- 配置日志 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
</configuration>
12. 配置applicationContext.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" 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"> <!-- bean definitions here -->
<!-- 扫描对应包下的注解 -->
<context:component-scan base-package="com.qf"></context:component-scan>
<!-- 引入配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
<property name="url" value="${db.url}"></property>
<property name="driverClassName" value="${db.driver}"></property>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 必选属性,配置dataSource数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 非必选属性,可引入mybatis-config.xml配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 非必选属性,当Mapper接口和对应的Mapper.xml文件不在同一目录时,
指定配置Mapper.xml文件的具体位置,这里使用的是通配符配置方式 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>
<!-- 扫描Mapper接口,生成代理对象 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qf.mapper"></property>
</bean>
</beans>
13. 测试
package com.qf.test;
import com.qf.controller.UserController;
import com.qf.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class SpringTest {
@Test
public void test_findAll(){
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserController userController =
(UserController)applicationContext.getBean("userController");
List<User> list = userController.findAll();
System.out.println(list);
}
}
14. 补充:创建数据源配置类
可以将applicationContext.xml中数据源的相关配置注释掉,使用配置类完成配置
@PropertySource
作用:用于指定properties文件的位置
属性:value:指定文件的名称和路径。
关键字:classpath,表示类路径下等同于xml中: <context:property-placeholder location="classpath:db.properties"/>
@Configuration
作用:指定当前类是一个配置类,服务器启动后会先加载
@Bean
作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
属性: name和value: 用于指定bean的id,当不写时,默认值是当前方法的名称
package com.qf.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.util.Properties;
@PropertySource(value = "classpath:db.properties")
@Configuration
public class DataSourceConfig {
@Value("${db.driver}")
private String driverClassName;
@Value("${db.url}")
private String url;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource(){
Properties pro = new Properties();
pro.setProperty("url",url);
pro.setProperty("username",username);
pro.setProperty("password",password);
pro.setProperty("driverClassName",driverClassName);
DataSource dataSource = null;
try {
dataSource = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
}
15. 补充:添加分页操作
15.1添加依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
15.2 第一种方式:在 applicationContext.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" 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"> <!-- bean definitions here -->
<!-- 扫描对应包下的注解 -->
<context:component-scan base-package="com.qf"></context:component-scan>
<!-- 引入配置文件-->
<!-- <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>-->
<!-- 配置数据源 -->
<!-- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">-->
<!-- <property name="username" value="${db.username}"></property>-->
<!-- <property name="password" value="${db.password}"></property>-->
<!-- <property name="url" value="${db.url}"></property>-->
<!-- <property name="driverClassName" value="${db.driver}"></property>-->
<!-- </bean>-->
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 必选属性,配置dataSource数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 非必选属性,可引入mybatis-config.xml配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 非必选属性,当Mapper接口和对应的Mapper.xml文件不在同一目录时,
指定配置Mapper.xml文件的具体位置,这里使用的是通配符配置方式 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
<!-- 分页配置 -->
<!-- 配置插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置参数,一行配置一个 -->
<value>
helperDialect=mysql
reasonable=true
supportMethodsArguments=true
</value>
</property>
</bean>
</array>
</property>
</bean>
<!-- 扫描Mapper接口,生成代理对象 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qf.mapper"></property>
</bean>
</beans>
15.3 第二种方式:在 mybatis-config.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>
<!-- 配置日志 -->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
<property name="reasonable" value="true"/>
<property name="supportMethodsArguments" value="true"/>
</plugin>
</plugins>
</configuration>
15.4 在 UserController 中添加方法
public PageInfo<User> findByPage(Integer pageNum,Integer pageSize){
PageHelper.startPage(pageNum,pageSize);
List<User> userList = userService.findAll();
PageInfo<User> userPageInfo = new PageInfo<>(userList);
return userPageInfo;
}
15.5 测试
@Test
public void test_findByPage(){
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserController userController =
(UserController)applicationContext.getBean("userController");
PageInfo<User> pageInfo = userController.findByPage(0,2);
System.out.println(pageInfo.getList());
}