一、导入相关的包
junit 包 Mybatis包 mysql数据库包 Spring相关的包 Aop相关的包
Mybatis-Spring包(现在就来学这个)
提示jdk版本不一致的朋友记得 jdk8只支持spring到5.x 所以如果导入的spring(spring-webmvc spring-jdbc)大于5.x 就需要降级或者安装jdk17否则就会报错;jdk8跟着我导入的包的版本来是没问题的
配置文件如下:
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.example</groupId>
<artifactId>SpringFather</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>SpringSon10</artifactId>
<packaging>war</packaging>
<name>SpringSon10 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--导入junit支持-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
<!--导入AOP支持-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--导入mysql支持 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--导入Mybatis支持 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--导入Spring支持 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--Spring操作数据库的话还需要导入一个spring-jdbc 支持 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--Mybatis和Spring整合的包-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--导入lombok包好写实体类的时候偷懒-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<!--导入log4j相关依赖-->
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<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>
</dependencies>
<build>
<finalName>SpringSon10</finalName>
<!--解决配置文件无法导出或生效的问题(一般加在父工程)-->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
二、回忆一下Mybatis怎么实现的
创建实体类
package com.li.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private int id;
private String name;
private String pwd;
}
创建增删改查接口
package com.li.dao;
import com.li.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
}
创建工具类获取sqlSessionFactory
package com.li.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 {
//官网上有三段代码拿来用 工具类的作用就是得到SqlSession
private static final SqlSessionFactory sqlSessionFactory;
static{
try {
//获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//获取SqlSession
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
创建接口Mapper.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等于绑定一个对应的Mapper接口 我这里是UserMapper接口-->
<mapper namespace="com.li.dao.UserMapper">
<!-- 这里没有写sql语句-->
<select id="selectAll" resultType="user">
select *from mybatis1.user
</select>
</mapper>
原来的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>
<!--通过properties标签引入外部配置文件-->
<properties resource="db.properties"/>
<!--给实体类取别名-->
<typeAliases>
<package name="com.li.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${urlName}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 绑定mapper-->
<mappers>
<mapper resource="com/li/dao/UserMapper.xml"/>
<!--<!– <!–也可以通过class绑定mapper–>-->
<!-- <mapper class="com.li.mapper.UserMapper"/>-->
<!--<!– –>–>-->
</mappers>
</configuration>
和mybatis-config.xml相对应的配置文件
driver=com.mysql.jdbc.Driver
urlName=jdbc:mysql://localhost:3306/mybatis1?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
测试类测试能不能跑通
package com.li.dao;
import com.li.pojo.User;
import com.li.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class Testgo {
@Test
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
for (User user : mapper.selectAll()) {
System.out.println(user);
}
sqlSession.close();
}
}
目录结构
三、Mybatis-Spring
1、什么是Mybatis-spring
2、编写Mybatis-spring的xml配置文件
直接用spring的配置文件格式
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
配置数据库连接的数据,相当于Mybatis的连接数据库那一段
<!--DataSource:使用Spring的数据源替换Mybatis的配置 还可以用c3p0 dbcp druid-->
<!--这里相当于配置连接数据库-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis1?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
相当于这一段
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${urlName}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
得到sqlSessionFactory
<!--得到sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--这里 ref后面值就是我们上面配置的数据库来连接的id值 -->
<property name="dataSource" ref="dataSource"/>
<!--这里可以实现Mybatis配置文件里的所有东西,基本上就可以不要mybatis配置文件了,但是有的时候mybatis配置文件还是有一定的作用
一般会把取别名和设置放在mybatis的配置文件中去做
-->
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--也可以注册mapper映射器-->
<property name="mapperLocations" value="classpath:com/li/dao/UserMapper.xml"/>
</bean>
配置文件之前相当于下面这一段
package com.li.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 {
//官网上有三段代码拿来用 工具类的作用就是得到SqlSession
private static final SqlSessionFactory sqlSessionFactory;
static{
try {
//获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//获取SqlSession
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
配置文件下面那两段相当于mybatis核心配置文件中的配置之类的(有一一对应的property 设置)
得到sqlSession 在mybatis-spring中叫sqlSessionTemplat
<!--得到sqlSession,在mybatis-spring中叫sqlSessionTemplat可以简答的理解她两就是一个意思-->
<!--这里需要给SqlSessionTemplate注入一个参数 -->
<bean id="sqlSessionT" class="org.mybatis.spring.SqlSessionTemplate">
<!--这里只能用构造器注入,因为没有set方法 -->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
在mybatis中我们在配置文件中就可以写sql语句,但是这里链接Spring了之后配置是面向对象的,需要创建一个实现类来写sql语句
package com.li.dao;
import com.li.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper{
//之前我们所有的操作都是用sqlSession来执行,现在我们用sqlSessionTemplat来执行的
//使用spring需要注入,需要有set方法,spring万物皆注入
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> selectAll() {
//这里的操作就是和拿到SqlSession之后拿mapper的方法是一样的
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectAll();
}
}
写完类之后就需要在配置文件中注入
<!--注入写的拿到写sql语句的类-->
<bean id="userMapper" class="com.li.dao.UserMapperImpl">
<!--得到sqlSessionTempla-->
<property name="sqlSessionTemplate" ref="sqlSessionTempla"/>
</bean>
配置完成之后我们来写测试类测试
package com.li.dao;
import com.li.pojo.User;
import com.li.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Testgo {
@Test
public void test1(){
// SqlSession sqlSession = MybatisUtils.getSqlSession();
//
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//
// for (User user : mapper.selectAll()) {
// System.out.println(user);
// }
//
// sqlSession.close();
ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
UserMapper mapper = context.getBean("userMapper", UserMapper.class);
for (User user : mapper.selectAll()) {
System.out.println(user);
}
}
}
完整的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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的数据源替换Mybatis的配置 还可以用c3p0 dbcp druid-->
<!--这里相当于配置连接数据库-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis1?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--得到sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--这里 ref后面值就是我们上面配置的数据库来连接的id值 -->
<property name="dataSource" ref="dataSource"/>
<!--这里可以实现Mybatis配置文件里的所有东西,基本上就可以不要mybatis配置文件了,但是有的时候mybatis配置文件还是有一定的作用
一般会把取别名和设置放在mybatis的配置文件中去做
-->
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--也可以注册mapper映射器-->
<property name="mapperLocations" value="classpath:com/li/dao/UserMapper.xml"/>
</bean>
<!--得到sqlSession,在mybatis-spring中叫sqlSessionTemplat可以简答的理解她两就是一个意思-->
<!--这里需要给SqlSessionTemplate注入一个参数 -->
<bean id="sqlSessionT" class="org.mybatis.spring.SqlSessionTemplate">
<!--这里只能用构造器注入,因为没有set方法 -->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--注入写的拿到写sql语句的类-->
<bean id="userMapper" class="com.li.dao.UserMapperImpl">
<!--得到sqlSessionTemplate-->
<property name="sqlSessionTemplate" ref="sqlSessionT"/>
</bean>
</beans>
需要注意的是UserMapper的配置文件不能把里面的sql语句部分删除,要不然会报
Invalid bound statement (not found) 的错
<?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等于绑定一个对应的Mapper接口 我这里是UserMapper接口-->
<mapper namespace="com.li.dao.UserMapper">
<!-- 这里没有写sql语句-->
<select id="selectAll" resultType="user">
select *from mybatis1.user
</select>
</mapper>