SpringBoot整合Mybutis
2019-12-09 本文已影响0人
琳媚儿
-
导入对应的包
image
扫描接口(BoopMapping)
@SpringBootApplication
@MapperScan("dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- application.properties: 添加自己的服务器
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
重点:全局配置
mybatis.mapper-locations=classpath:mapping/BookMapping.xml
mybatis.type-aliases-package=pojo
- BookMapping 接口
@Repository
public interface BookMapping {
void addBook(Book book);
Book loadBook(int id);
List<Book> findAllBook(Book book);
void updataBook(@Param("id") int id, @Param("book") Book book);
Book deleteBook(int id);
}
- 新建类controller
@RestController
public class TestController {
@Autowired
private BookMapping bookMapping;
@RequestMapping(value = "/books",method = RequestMethod.POST)
public Book loadBook(Book book){
bookMapping.addBook(book);
return book;
}
@RequestMapping(value = "/books/{id}",method = RequestMethod.GET)
public Book loadBook(@PathVariable int id){
return bookMapping.loadBook(id);
}
@RequestMapping(value = "/books",method = RequestMethod.GET)
public Book findAllBook(Book book){
bookMapping.findAllBook(book);
return book;
}
@RequestMapping(value = "/books/{id}",method = RequestMethod.PUT)
public Book updataBook(@PathVariable int id,@RequestBody Book book){
bookMapping.updataBook(id,book);
book.setId(id);
return book;
}
@RequestMapping(value = "/books/{id}",method = RequestMethod.DELETE)
public Book updataBook(@PathVariable int id){
return bookMapping.deleteBook(id);
}
}
BookMapping.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="dao.BookMapping">
<insert id="addBook" parameterType="pojo.Book" useGeneratedKeys="true" keyProperty="">
insert into user (uname) values (#{uname})
</insert>
<select id="loadBook" resultType="pojo.Book">
select * from user where id = #{id}
</select>
<select id="findAllBook" parameterType="pojo.Book">
select * from user
</select>
<update id="updataBook" keyProperty="id">
update user set uname=#{book.uname} where id=#{id}
</update>
</mapper>
- 测试:New HTTP Request:/ http://localhost:8080/books
POST http://localhost:8080/books
Content-Type: application/json
{"uname":"Hello"}
###
GET http://localhost:8080/books/1
Accept: application/json
###
GET http://localhost:8080/books
Accept: application/json
###
PUT http://localhost:8080/books/41
Content-Type: application/json
{"uname":"Hello"}
###
DELETE http://localhost:8080/books/40
Accept: application/json
###