简介:
原名iBatis,SpringBoot中使用MyBatis:
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
2.数据库表,实体类以及配置文件与上一章JdbcTemplate那没有区别,
3.从下往上写,dao层:还是一样的,增删改查查询所有方法
@Mapper public interface BookMapper { int addBook(Book book); int deleteBookById(Integer id); int updateBookById(Book book); Book getBookById(Integer id); List<Book> getAllBooks(); }
<?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="org.sang.mapper.BookMapper">
<insert id="addBook" parameterType="org.sang.model.Book"> INSERT INTO book(name,author) VALUES (#{name},#{author}) </insert>
<delete id="deleteBookById" parameterType="int"> DELETE FROM book WHERE id=#{id} </delete>
<update id="updateBookById" parameterType="org.sang.model.Book"> UPDATE book set name=#{name},author=#{author} WHERE id=#{id} </update>
<select id="getBookById" parameterType="int" resultType="org.sang.model.Book"> SELECT * FROM book WHERE id=#{id} </select>
<select id="getAllBooks" resultType="org.sang.model.Book"> SELECT * FROM book </select> </mapper>
4.service:
@Service public class BookService { @Autowired BookMapper bookMapper; public int addBook(Book book) { return bookMapper.addBook(book); } public int updateBook(Book book) { return bookMapper.updateBookById(book); } public int deleteBookById(Integer id) { return bookMapper.deleteBookById(id); } public Book getBookById(Integer id) { return bookMapper.getBookById(id); } public List<Book> getAllBooks() { return bookMapper.getAllBooks(); } }
5.controller:
@RestController public class BookController { @Autowired BookService bookService; @GetMapping("/bookOps") 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(1); 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(2); System.out.println("deleteBookById>>>"+delete); List<Book> allBooks = bookService.getAllBooks(); System.out.println("getAllBooks>>>"+allBooks); } }