Mybatis-Spring整合
项目源码地址
GitHub | https://github.com/Web-Learn-GSF/Java_Learn_Examples |
---|---|
父工程 | Java_Framework_Spring |
子工程 | Integrate_Mybatis_First_Way |
Integrate_Mybatis_Second_Way |
环境搭建
项目环境
1、Maven搭建
2、依赖
<dependencies>
<!-- 将mybatis无缝整合到spring中 -->
<!-- 3+版本的mybatis-spring包需要3.5+的mybatis和6+的spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.14</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.1.1</version>
</dependency>
<!-- sql数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>
数据库环境
数据库基本信息
属性 | 值 |
---|---|
数据库名字 | learn_mybatis |
用户名 | root |
密码 | 123456 |
建表
-- 建表
CREATE TABLE `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
-- 插入语句
INSERT INTO `user`(`id`, `name`, `pwd`) VALUES
(1, "狂神", "123456"),
(2, "张三", "1234567"),
(3, "李四", "1234568")
整合-方法1
将通过对比的方法,讲述纯粹mybatis和整合spring-mybatis之间的区别
整体结构对比
纯粹mybatis Vs 整合spring-mybatis
配置文件对比
内容 | 纯粹mybatis | 整合spring-mybatis |
---|---|---|
sqlSessionFactory、sqlSession的定义获取 | Utils/MybatisUtils | resources/spring-dao.xml |
dataSource数据库连接、mapper.xml文件映射 | resources/mybatis-config.xml | resources/spring-dao.xml |
- 上表第二行扩展:对于整合spring-mybatis,可以把
resources/mybatis-config.xml
的所有内容,搬进resources/spring-dao.xml
,留下resources/mybatis-config.xml
可以表明该项目是整合了mybatis
对比文件之间的差异
文件 | 纯粹mybatis | 整合spring-mybatis |
---|---|---|
Utils/MybatisUtils | 有 | 无,整合到xml文件,通过管理bean获取 |
Dao/UserDaoImpl | 无,不需要通过实现类来管理bean | 有 |
共有相同的代码
- UserDao
package GSF.Example.Dao;
import GSF.Example.Pojo.User;
import java.util.List;
import java.util.Map;
public interface UserDao {
List<User> getUserList();
// 根据id查询用户
User getUserById(int id);
//插入一个用户
int addUser(User user);
// 用map的方式插入用户
int addUserByMap(Map<String, Object> map);
//修改用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
- UserDao.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">
<!-- namespace=绑定一个Dao/Mapper接口-->
<mapper namespace="GSF.Example.Dao.UserDao">
<resultMap id="UserMap" type="GSF.Example.Pojo.User">
<!-- column:数据库中的列名;property:实体类中的属性名,一样的就无需再配置进来(配置了也不影响)-->
<result column="pwd" property="password"/>
</resultMap>
<!-- select查询语句,ID对应方法名-->
<select id="getUserList" resultMap="UserMap">
select id, name, pwd from learn_mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="GSF.Example.Pojo.User">
select id, name, pwd as password from learn_mybatis.user where id=#{id}
</select>
<insert id="addUser" parameterType="GSF.Example.Pojo.User">
insert into learn_mybatis.user(id, name, pwd) values (#{id}, #{name}, #{password});
</insert>
<insert id="addUserByMap" parameterType="map">
insert into learn_mybatis.user(id, name, pwd) values (#{user_id}, #{user_name}, #{user_pwd});
</insert>
<update id="updateUser" parameterType="GSF.Example.Pojo.User">
update learn_mybatis.user set name=#{name}, pwd=#{password} where id=#{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from learn_mybatis.user where id=#{id};
</delete>
</mapper>
- Pojo/User
package GSF.Example.Pojo;
public class User {
private int id;
private String name;
private String password;
public User(){
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
不同及特有的代码-整合spring-mybatis
UserDaoImpl
该实现类用于在spring中管理,注册为bean
package GSF.Example.Dao;
import GSF.Example.Pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
import java.util.Map;
public class UserDaoImpl implements UserDao{
// 注入sqlSession
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
@Override
public List<User> getUserList() {
return sqlSession.getMapper(UserDao.class).getUserList();
}
@Override
public User getUserById(int id) {
return sqlSession.getMapper(UserDao.class).getUserById(id);
}
@Override
public int addUser(User user) {
return sqlSession.getMapper(UserDao.class).addUser(user);
}
@Override
public int addUserByMap(Map<String, Object> map) {
return sqlSession.getMapper(UserDao.class).addUserByMap(map);
}
@Override
public int updateUser(User user) {
return sqlSession.getMapper(UserDao.class).updateUser(user);
}
@Override
public int deleteUser(int id) {
return sqlSession.getMapper(UserDao.class).deleteUser(id);
}
}
resources/spring-dao.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- sqlSessionFactory的bean注册 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 可以绑定mybatis的所有有关配置文件 -->
<!-- 绑定mybatis核心配置文件,也可以不绑定,用property参数实现核心配置文件里面的所有功能 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 绑定mapper.xml文件:可以不在这里绑定,在mybatis核心配置文件中绑定-->
<!-- 这个版本下,用路径统配符,必须用classpath*,不能用classpath -->
<property name="mapperLocations" value="classpath*:GSF/Example/Dao/*.xml"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/learn_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 获取sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userDaoImpl" class="GSF.Example.Dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
- 该文件可以完全替代mybatis-config.xml文件的内容
- 为了体现是对mybatis的整合,留着mybatis-config.xml文件
测试代码
package GSF.Example.Dao;
import GSF.Example.Pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.HashMap;
import java.util.List;
public class UserTest {
@Test
public void GetUserList(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
List<User> user = userDaoImpl.getUserList();
System.out.println(user);
}
@Test
public void GetUserById(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
User userById = userDaoImpl.getUserById(2);
System.out.println(userById);
}
@Test
public void AddUser(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
int addUser = userDaoImpl.addUser(new User(25, "GSF", "qwerty"));
System.out.println(addUser);
}
@Test
public void AddUserByMap(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
// 插入成功,返回值为1
HashMap<String, Object> map_obj = new HashMap<>();
map_obj.put("user_id", 22);
map_obj.put("user_name", "121212");
map_obj.put("user_pwd", "zxcxvz");
int addUserByMap = userDaoImpl.addUserByMap(map_obj);
System.out.println(addUserByMap);
}
@Test
public void UpdateUser(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
int updateUser = userDaoImpl.updateUser(new User(25, "GSF-change", "qwerty"));
System.out.println(updateUser);
}
@Test
public void DeleteUser(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserDao userDaoImpl = (UserDao) context.getBean("userDaoImpl");
int updateUser = userDaoImpl.deleteUser(2);
System.out.println(updateUser);
}
}
不同及特有的代码-纯粹mybatis
Utils/MybatisUtils
package GSF.Example.Utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
String resources = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resources);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static SqlSession getSqlsession(){
return sqlSessionFactory.openSession();
}
}
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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/learn_mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper resource="GSF/Example/Dao/UserMapper.xml"/>
</mappers>
</configuration>
测试代码
package GSF.Example.Dao;
import GSF.Example.Pojo.User;
import GSF.Example.Utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
public class UserTest {
@Test
public void GetUserList(){
// 官方建议用try...catch包裹,可以不用
SqlSession sqlsession = MybatisUtils.getSqlsession();
try {
UserDao mapper = sqlsession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sqlsession.close();
}
}
@Test
public void GetUserById(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserDao mapper = sqlsession.getMapper(UserDao.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlsession.close();
}
@Test
public void AddUser(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserDao mapper = sqlsession.getMapper(UserDao.class);
// 插入成功,返回值为1
int flag = mapper.addUser(new User(10, "GSF", "qwerty"));
System.out.println(flag);
sqlsession.commit();
sqlsession.close();
}
@Test
public void AddUserByMap(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserDao mapper = sqlsession.getMapper(UserDao.class);
// 插入成功,返回值为1
HashMap<String, Object> map_obj = new HashMap<>();
map_obj.put("user_id", 12);
map_obj.put("user_name", "121212");
map_obj.put("user_pwd", "zxcxvz");
int flag = mapper.addUserByMap(map_obj);
System.out.println(flag);
sqlsession.commit();
sqlsession.close();
}
@Test
public void UpdateUser(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserDao mapper = sqlsession.getMapper(UserDao.class);
int flag = mapper.updateUser(new User(1, "123", "12345678"));
System.out.println(flag);
sqlsession.commit();
sqlsession.close();
}
@Test
public void DeleteUser(){
SqlSession sqlsession = MybatisUtils.getSqlsession();
UserDao mapper = sqlsession.getMapper(UserDao.class);
int flag = mapper.deleteUser(1);
System.out.println(flag);
sqlsession.commit();
sqlsession.close();
}
}
整合-方法2
改动点:sqlSession的获取
方法1中sqlSession的获取:通过bean配置,获取sqlSessionFactory,进而获取到sqlSession,并注入到相关实现类中
方法2中sqlSession的获取:通过让UserDaoImpl实现类继承SqlSessionDaoSupport,通过getSqlSession()方法来获取sqlSession
代码改动
UserDaoImpl
package GSF.Example.Dao;
import GSF.Example.Pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
import java.util.Map;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
@Override
public List<User> getUserList() {
return getSqlSession().getMapper(UserDao.class).getUserList();
}
@Override
public User getUserById(int id) {
return getSqlSession().getMapper(UserDao.class).getUserById(id);
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserDao.class).addUser(user);
}
@Override
public int addUserByMap(Map<String, Object> map) {
return getSqlSession().getMapper(UserDao.class).addUserByMap(map);
}
@Override
public int updateUser(User user) {
return getSqlSession().getMapper(UserDao.class).updateUser(user);
}
@Override
public int deleteUser(int id) {
return getSqlSession().getMapper(UserDao.class).deleteUser(id);
}
}
spring-dao.xml
<!-- 共有的代码:sqlSessionFactory的bean注册 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 可以绑定mybatis的所有有关配置文件 -->
<!-- 绑定mybatis核心配置文件,也可以不绑定,用property参数实现核心配置文件里面的所有功能 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 绑定mapper.xml文件:可以不在这里绑定,在mybatis核心配置文件中绑定-->
<!-- 这个版本下,用路径统配符,必须用classpath*,不能用classpath -->
<property name="mapperLocations" value="classpath*:GSF/Example/Dao/*.xml"/>
</bean>
<!-- 改动前 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="userDaoImpl" class="GSF.Example.Dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
<!-- 改动后 -->
<bean id="userDaoImpl" class="GSF.Example.Dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
Mybatis-Spring-SpringMVC整合(SSM)
项目源码地址
GitHub | https://github.com/Web-Learn-GSF/Java_Learn_Examples |
---|---|
父工程 | Java_Framework_IntegrateSSM |
子工程 | Tomcat9-Maven3.9.5-Mysql5.7.31 |
环境搭建
项目环境要求
环境 | 版本 |
---|---|
MySQL | 5.7.31 |
Maven | 3.9.5 |
Tomcat | 9.x |
用IDEA,创建一个web环境,并导入相关依赖:
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring、SpringMVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
数据库环境
-- 建表
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
-- 写入数据
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
项目整体框架
文件(从上到下捋) | 归属 | 作用 |
---|---|---|
BookController | SpringMVC,Controller | 完成url请求逻辑的处理和View视图结果的响应 |
BookMapper、BookMapper.xml | Mybatis,Dao | 定义方法完成对应的数据库操作逻辑,返回处理后的数据库数据 |
Books | Mybatis,pojo | 数据库中数据表对应的实体类对象 |
BookService、BookServiceImpl | Mybatis,业务处理 | 处理数据的逻辑、算法和规则:将数据传递给Dao层,同时给Controller层提供数据接口 |
spring-dao.xml、database.properties | Mybatis,Spring | 定义数据库连接、sqlSessionFactory的bean注册,Mapper的自动扫描和注册 |
spring-mvc.xml | SpringMVC,Spring | 允许注解、静态资源过滤、controller的包扫描和自动注册、视图解析器ViewResolver |
spring-service.xml | Mybatis,Spring | 扫描注册service下的包并注册bean、声明事务管理器、织入AOP事务管理 |
applicationContext.xml【核心文件】 | Spring | 负责import:spring-dao.xml、spring-mvc.xml、spring-service.xml三个包 |
mybatis-config.xml | Mybatis | 给类起别名 |
addBook.jsp、allBook.jsp、updateBook.jsp、index.jsp | SpringMVC,View | 视图,用于展示给用户的各种页面 |
web.xml | SpringMVC | 配置DispatcherServlet、完成乱码过滤 |
MyTest | Web | 测试bean获取 |
SSM整体和单独对比
有见解了,就回来补充