SpringBoot整合MyBatis
一、添加依赖
https://mvnrepository.com/
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency>
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
二、项目结构和配置如下:
application.properties
#是否开启缓存,开发时可设置为false,默认为true spring.thymeleaf.cache=false #检查模板是否存在,默认为true spring.thymeleaf.check-template=true #检查模板位置是否存在,默认为true spring.thymeleaf.check-template-location=true #模板文件编码,UTF-8 spring.thymeleaf.encoding=UTF-8 #模板文件位置 spring.thymeleaf.prefix=classpath:/templates #Content-Type配置 spring.thymeleaf.servlet.content-type=text/html #模板文件后缀 spring.thymeleaf.suffix=.html #启用MVC Thymeleaf视图分辨率 spring.thymeleaf.enabled=true #模板编码 spring.thymeleaf.mode=LEGACYHTML5 #应该中解决方案中排除的视图名称的逗号分隔列表 spring.thymeleaf.excluded-view-names= #root日志以 WARN 级别输出 (日志只输出 WARN 及以上级别的信息) #logging.level.root=WARN #springframework.web 日志只以 DEBUG 级别输出 #logging.level.org.springframework.web=DEBUG #hibernate 日志以 ERROR 级别输出 #logging.level.org.hibernate=ERROR logging.file.name=e:\\log\\info.log logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n logging.pattern.file=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n #数据源配置 spring.datasource.name=test spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #加上?useUnicode=true&characterEncoding=UTF-8,否则可能插入数据库中文乱码 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/vhr?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver #spring.datasource.sql-script-encoding=UTF-8 #spring.datasource.druid.filter.encoding.enabled=true spring.datasource.druid.filters=stat spring.datasource.druid.max-active=20 spring.datasource.druid.initial-size=1 spring.datasource.druid.max-wait=60000 spring.datasource.druid.min-idle=1 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.validation-query=select 'x' spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-open-prepared-statements=20 #所有的mapper映射文件 #mybatis.mapper-locations=classpath*:com/springboot/mapper/*.xml #resource下的mapper映射文件 #mybatis.mapper-locations=classpath*:mapper/**/*.xml mybatis.mapper-locations=classpath:mapper/BookMapper.xml mybatis.config-location=classpath:mybatis/mybatis-config.xml pagehelper.helper-dialect=mysql pagehelper.reasonable=true pagehelper.support-methods-arguments=true pagehelper.params=count=countSql
三、代码如下:
mybatis/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> </configuration>
package com.example.pojo; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.util.Date; public class Book implements Serializable { private Integer id; private String name; private String author; @JsonIgnore private Float price; @JsonFormat(pattern = "yyyy-MM-dd") private Date publicationDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public Date getPublicationDate() { return publicationDate; } public void setPublicationDate(Date publicationDate) { this.publicationDate = publicationDate; } }
package com.example.mapper; import com.example.pojo.Book; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface BookMapper { int addBook(Book book); int deleteBookById(Integer id); int updateBook(Book book); Book getBookById(Integer id); List<Book> getAllBooks(); }
mapper/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.example.mapper.BookMapper"> <insert id="addBook" parameterType="com.example.pojo.Book"> INSERT INTO book(name,author) VALUES (#{name},#{author}) </insert> <delete id="deleteBookById" parameterType="int"> delete from book where id=#{id} </delete> <update id="updateBook" parameterType="com.example.pojo.Book"> update book set name=#{name},author=#{author} where id=#{id} </update> <select id="getBookById" parameterType="int" resultType="com.example.pojo.Book"> select * from book where id=#{id} </select> <select id="getAllBooks" resultType="com.example.pojo.Book"> select * from book </select> </mapper>
package com.example.service; import com.example.pojo.Book; import java.util.List; public interface BookService { int addBook(Book book); int updateBook(Book book); int deleteBookById(Integer id); Book getBookById(Integer id); List<Book> getAllBooks(); List<Book> findBooks(int page, int rows); }
package com.example.service; import com.example.mapper.BookMapper; import com.example.pojo.Book; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class BookServiceImpl implements BookService{ @Resource//@Autowired BookMapper bookMapper; @Override public int addBook(Book book) { return bookMapper.addBook(book); } @Override public int updateBook(Book book) { return bookMapper.updateBook(book); } @Override public int deleteBookById(Integer id) { return bookMapper.deleteBookById(id); } @Override public Book getBookById(Integer id) { return bookMapper.getBookById(id); } @Override public List<Book> getAllBooks() { return bookMapper.getAllBooks(); } @Override public List<Book> findBooks(int page, int rows) { PageHelper.startPage(page,rows); return bookMapper.getAllBooks(); } }
package com.example.controller; import com.example.pojo.Book; import com.example.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.Date; import java.util.List; @Controller public class BookController { //@Autowired @Resource private BookService bookService; @RequestMapping("/saveBook") @ResponseBody public String saveBook(){ Book book = new Book(); book.setAuthor("罗贯中"); book.setName("三国演义"); bookService.addBook(book); return "success"; } @RequestMapping("/findBooks/{page}/{rows}") @ResponseBody public List<Book> findBooks(@PathVariable int page,@PathVariable int rows){ return bookService.findBooks(page,rows); } @GetMapping("/book") @ResponseBody public Book book(){ Book book = new Book(); book.setAuthor("罗贯中"); book.setName("三国演义"); book.setPrice(48f); book.setPublicationDate(new Date()); return book; } @GetMapping("/bookOps")
@ResponseBody public void bookOps(){ Book b1 = new Book(); b1.setName("西厢记"); b1.setAuthor("王实甫"); int i = bookService.addBook(b1); System.out.println("addBook>>"+i); Book b2 = new Book(); b2.setId(2); b2.setName("朝花夕拾"); b2.setAuthor("鲁迅"); int updateBook = bookService.updateBook(b2); System.out.println("updateBook>>"+updateBook); Book b3 = bookService.getBookById(1); System.out.println("getBookById>>"+b3); int delete = bookService.deleteBookById(1); System.out.println("deleteBookById>>"+delete); List<Book> allBooks=bookService.getAllBooks(); System.out.println("getAllBooks>>>"+allBooks); } }
package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = {"com.example.controller","com.example.service"}) @MapperScan("com.example.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
四、测试