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>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>3.0.3version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.14version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>6.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.33version>
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")
将通过对比的方法,讲述纯粹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 |
resources/mybatis-config.xml
的所有内容,搬进resources/spring-dao.xml
,留下resources/mybatis-config.xml
可以表明该项目是整合了mybatis文件 | 纯粹mybatis | 整合spring-mybatis |
---|---|---|
Utils/MybatisUtils | 有 | 无,整合到xml文件,通过管理bean获取 |
Dao/UserDaoImpl | 无,不需要通过实现类来管理bean | 有 |
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);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="GSF.Example.Dao.UserDao">
<resultMap id="UserMap" type="GSF.Example.Pojo.User">
<result column="pwd" property="password"/>
resultMap>
<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>
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中管理,注册为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);
}
}
<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">
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<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>
<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);
}
}
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();
}
}
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>
<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();
}
}
方法1中sqlSession的获取:通过bean配置,获取sqlSessionFactory,进而获取到sqlSession,并注入到相关实现类中
方法2中sqlSession的获取:通过让UserDaoImpl实现类继承SqlSessionDaoSupport,通过getSqlSession()方法来获取sqlSession
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);
}
}
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<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>
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>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.9.RELEASEversion>
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获取 |
有见解了,就回来补充