springboot整合mybatis
程序员文章站
2022-04-09 20:22:28
1.创建一个SpringBoot项目,参考:http://www.cnblogs.com/i-tao/p/8878562.html 2.创建项目目录结构 3.整合Mybatis 3.1、在pom.xml文件里添加mysql连接驱动和mybatis依赖 3.2、application.properti ......
官方文档:mybatis-spring-boot-autoconfigure
1.新建项目导入依赖
添加web模块,jdbc模块,mysql驱动模块
相关依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2. 配置数据源和mybatis
spring.datasource.username=root
spring.datasource.password=18170021
spring.datasource.url=jdbc:mysql://localhost:3306/books?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置mybatis
mybatis.type-aliases-package=com.wang.entity
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# 数据库字段和实体类字段驼峰
mybatis.configuration.map-underscore-to-camel-case=true
3. 写实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private String recID;
private String title;
private String bookType;
private Double price;
}
4. mapper接口及mapper.xml
BookMapper
//这个注解表示了这是一个mybatis得mapper类
@Mapper
@Repository //@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。
public interface BookMapper {
List<Book> queryBooks();
Book queryBookById(@Param("recID") String id);
boolean addBook(Book book);
boolean updateBook(Book book);
boolean deleteBook(@Param("recID") String id);
}
BookMapper.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.wang.mapper.BookMapper">
<select id="queryBooks" resultType="Book">
select * from book;
</select>
<select id="queryBookById" resultType="Book">
select * from book where recID=#{recID};
</select>
<delete id="deleteBook">
delete from book where recID=#{recID};
</delete>
<insert id="addBook" parameterType="Book">
insert into book(recID,title,book_type,price) values (#{recID},#{title},#{bookType},#{price});
</insert>
<update id="updateBook" parameterType="Book">
update book set title = #{title},book_type=#{bookType},price=#{price} where recID=#{recID};
</update>
</mapper>
5. service层调mapper层测试
本文地址:https://blog.csdn.net/fjd7474/article/details/112537645
上一篇: C++基础学习10:继承
推荐阅读