学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy
但行好事,莫问前程
一、整合MyBatis
1.1 相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入器
- mybatis-spring整合包
重点
- 在此还可以导入了lombok包,不导入也可以(看你喜不喜欢用)
- 连接池用不用都可以
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.22</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.11</version>
</dependency>
配置Maven静态资源过滤问题!
<build>
<!--静态资源导出问题 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
1.2 回忆mybatis
- 数据库8.0版本,创建数据库mybatis
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for blog
-- ----------------------------
DROP TABLE IF EXISTS `blog`;
CREATE TABLE `blog` (
`id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客id',
`title` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客标题',
`author` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '博客作者',
`create_time` datetime NOT NULL COMMENT '创建时间',
`views` int NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of blog
-- ----------------------------
INSERT INTO `blog` VALUES ('0a547141ea664a438268c8f20e5dd049', 'Spring如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
INSERT INTO `blog` VALUES ('0e4cd725e18549cca0fb7fba317fb82a', '微服务如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
INSERT INTO `blog` VALUES ('146474f0cb1349369d345285b46e0205', 'Mybatis如此简单', '狂神过', '2022-07-30 17:11:19', 1000);
INSERT INTO `blog` VALUES ('2e08249e74d44b12910f16986b49fcd5', 'Java如此简单', '狂神过', '2022-07-30 17:11:20', 9999);
SET FOREIGN_KEY_CHECKS = 1;
- 编写pojo实体类
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
@Override
public String toString() {
return "Blog{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", createTime=" + createTime +
", views=" + views +
'}';
}
}
- 编写实现mybatis的配置文件
druid.properties
druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/mybatis?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
druid.username=root
druid.password=root
使用连接池需要写数据源适配器DruidDataSourceFactory
public class DruidDataSourceFactory extends UnpooledDataSourceFactory {
public DruidDataSourceFactory() {
this.dataSource = new DruidDataSource();
}
}
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 resource="druid.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="pers.tianyu.pojo"/>
</typeAliases>
<environments default="druidDataSource">
<environment id="druidDataSource">
<transactionManager type="JDBC"/>
<dataSource type="pers.tianyu.utils.DruidDataSourceFactory">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="pers/tianyu/dao/BlogMapper.xml"/>
</mappers>
</configuration>
- 编写BlogMapper接口
public interface BlogMapper {
public int insertByBlog(Blog blog);
public int deleteById(int id);
public int updateByBlog(Blog blog);
public List<Blog> queryBlog();
}
- 编写BlogMapper.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="pers.tianyu.dao.BlogMapper">
<select id="queryBlog" resultType="blog">
select * from Blog
</select>
</mapper>
- 测试
@Test
public void queryBlogTest() throws IOException {
String resource = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sqlSessionFactory.openSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
for (Blog blog : mapper.queryBlog()) {
System.out.println(blog);
}
}
1.3 Mybatis-Spring
1.3.1 介绍
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
文档链接
如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
1.3.2 整合实现一
- 创建Spring配置文件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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
</beans>
- 配置数据源替换mybaits的数据源
方式一:引入druid.properties文件
<!--方式一:不建议使用了-->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:druid.properties"/>
</bean>
<!--druid连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.driverClassName}"/>
<property name="url" value="${druid.url}"/>
<property name="username" value="${druid.username}"/>
<property name="password" value="${druid.password}"/>
</bean>
方式二:引入druid.properties文件
<!--方式二:context标签 可以一次加载多个,使用通配符*.properties-->
<context:property-placeholder location="classpath:druid.properties"/>
<!--druid连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.driverClassName}"/>
<property name="url" value="${druid.url}"/>
<property name="username" value="${druid.username}"/>
<property name="password" value="${druid.password}"/>
</bean>
方式三:引入druid.properties文件
<!--方式三-->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:druid.properties"/>
</bean>
<!--druid连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName">
<value>#{configProperties['druid.driverClassName']}</value>
</property>
<property name="url">
<value>#{configProperties['druid.url']}</value>
</property>
<property name="username">
<value>#{configProperties['druid.username']}</value>
</property>
<property name="password">
<value>#{configProperties['druid.password']}</value>
</property>
</bean>
如果druid.properties内名称格式不是 名字.名字(druid.password) 就会出现错误,有没有懂得讲一讲,学习一下。
- 配置SqlSessionFactory,关联MyBatis
<!--配置sqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--关联mybatis文件,这样一些配置可以写在mybatis-config.xml,层次分明-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--<property name="mapperLocations" value="classpath:pers/tianyu/dao/BlogMapper.xml"/>-->
</bean>
- 注册sqlSessionTemplate,关联sqlSessionFactory
<!--获取sqlSession对象-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造方法将sqlSessionFactory传入,因为没有set,所以用set就报错-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 将配置引入applicationContext.xml中
<!--引入spring-dao.xml配置-->
<import resource="spring-dao.xml"/>
- 需要UserMapper接口的UserMapperImpl 实现类,私有化sqlSessionTemplate
public class BlogMapperImpl implements BlogMapper {
// 在原来我们的所有操作,都使用sqlSession来执行,现在都使用SqlSessionTemplate,
// 现在使用sqlSessionTemplate,这两个本质一样。
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public int insertByBlog(Blog blog) {
return 0;
}
@Override
public int deleteById(int id) {
return 0;
}
@Override
public int updateByBlog(Blog blog) {
return 0;
}
@Override
public List<Blog> queryBlog() {
BlogMapper mapper = sqlSessionTemplate.getMapper(BlogMapper.class);
return mapper.queryBlog();
}
}
- 将自己写的实现类,注册到applicationContext.xml配置文件中。
<!--方式一:使用sqlSessionTemplate-->
<bean id="blogMapper" class="pers.tianyu.dao.BlogMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
- 测试使用即可!
@Test
public void queryBlogSpringTest1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BlogMapperImpl blogMapper = context.getBean("blogMapper", BlogMapperImpl.class);
for (Blog blog : blogMapper.queryBlog()) {
System.out.println(blog);
}
}
1.3.3 整合实现二
mybatis-spring1.2.3版以上的才有这个,官方文档截图:
dao继承Support类 , 直接利用 getSqlSession() 获得 , 然后直接注入SqlSessionFactory . 比起整合方式一 , 不需要管理SqlSessionTemplate , 而且对事务的支持更加友好 . 可跟踪源码查看。
- 将我们上面写的UserMapperImpl修改一下
public class BlogMapperImpl2 extends SqlSessionDaoSupport implements BlogMapper {
@Override
public int insertByBlog(Blog blog) {
return 0;
}
@Override
public int deleteById(int id) {
return 0;
}
@Override
public int updateByBlog(Blog blog) {
return 0;
}
@Override
public List<Blog> queryBlog() {
// 不需要在传进来SqlSessionTemplate,使用getSqlSession()方法获取就可以了。
BlogMapper mapper = getSqlSession().getMapper(BlogMapper.class);
return mapper.queryBlog();
}
}
- 注册到applicationContext.xml配置文件中。
<!--方式二:使用SqlSessionDaoSupport-->
<bean id="blogMapper2" class="pers.tianyu.dao.BlogMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 测试使用即可!
@Test
public void queryBlogSpringTest2(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BlogMapperImpl2 blogMapper = context.getBean("blogMapper2", BlogMapperImpl2.class);
for (Blog blog : blogMapper.queryBlog()) {
System.out.println(blog);
}
}