总结:
和SSM相比,
1)导入的包不同
2)不再有mybatis的核心配置文件了,也不同单独写db.properties了,以前“开启二级缓存,起别名”等在核心配置文件里的配置全都配置到application.properties里
3)@Mapper注解,代替了什么往下看吧!
1、新建project/module
选择如下模板
2、创建测试用的表
本来想直接用公司的表去测,但是除了查询,还要测试增删改,别不小心改数据了,不能拿公司的表测,笑死。那就拿之前建的book表去测吧
3、导入jar包
导入mybatis官方提供的整合用的jar包mybatis-spring-boot-starter(有的公司不用starter这个jar包,而是直接用mybatis-plus)
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
4、配置数据库
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/db_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5、创建pojo、mapper接口、mapper.xml配置文件、在springboot配置文件中配置mybatis
(1)pojo.Blog.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date create_time;
private int views;
}
(2)BlogMapper.java 接口
@Mapper
public interface BlogMapper {
//1.查找所有Blog
List<Blog> selectAllBlog();
//2.添加一个Blog
void addBlog(Blog blog);
//3.修改
void updateBlog(Map<String,Object> map);
//4.删除
void deleteBlogById(String id);
}
这里用到两个注解(二选一)@Mapper和@Repository,都是自动帮我们生成mapper接口的实现类MapperImpl.java,然后将实现类的实例直接注入到bean中,不需要我们再手动去写mapper接口的实现类。相当于SSM中我们配置的这一段:
但是在springboot中更简洁,有两种方法:
- @Mapper注解
- @Repository注解+@MapperScannerConfigurer注解
(3)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="com.example.demo.springbootmybatis.dao.BlogMapper">
<select id="selectAllBlog" resultType="blog">
select * from db_mybatis.blog
</select>
<insert id="addBlog" parameterType="blog">
insert into db_mybatis.blog
values (#{id},#{title},#{author},#{create_time},#{views})
</insert>
<update id="updateBlog" parameterType="map">
update db_mybatis.blog
SET title=#{title}
where id=#{id}
</update>
<delete id="deleteBlogById" parameterType="java.lang.String">
delete from db_mybatis.blog
where id=#{7/21}
</delete>
</mapper>
(4)在application.properties中整合mybatis
# 整合mybatis
mybatis.type-aliases-package=com.example.demo.springbootmybatis.pojo
mybatis.mapper-locations=这里看下面,会出错
(5)测试
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Resource
BlogMapper blogMapper;
@Test
void contextLoads() throws SQLException {
//查找
// List<Blog> blogs = blogMapper.selectAllBlog();
// System.out.println(blogs);
//增加
//blogMapper.addBlog(new Blog("7/21","怎么还不下班","小丁",new Date(),2));
//删除
blogMapper.deleteBlogById("7/21");
//修改
// Map<String, Object> map = new HashMap<>();
// map.put("id","7/21");
// map.put("title","还有两个小时下班");
// blogMapper.updateBlog(map);
}
}
出现问题:
报出了“invalid bound statement”问题,貌似在springboot中,xml配置文件只能放在resources下面吗(按照约定大于配置)?
修改后:
# 整合mybatis mybatis.mapper-locations=classpath:mybatis/mapper/*.xml