Mybatis层编写
- 数据库配置文件 database.properties
driver=com.mysql.jdbc.Driver
#如果使用的是mysql 8.0+ 需要增加一个时区的配置 &serverTimezone=Asia/Shanghai
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=huba
password=123456
-
IDEA关联数据库
-
编写Mybatis核心配置文件
<?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> <!--配置数据源,现在交给Spring完成--> <!--别名--> <typeAliases> <package name="com.kuang.pojo"/> </typeAliases> <!--设置--> <!--绑定mapper--> <mappers> <mapper class="com.kuang.dao.BookMapper"/> </mappers> </configuration>
-
实体类 Books
使用lombok!
@Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
-
dao层 BookMapper接口和BookMapper.xml
public interface BookMapper { //增加一本书 int addBook(Books books); //删除一本书 int deleteBookById(@Param("bookId") int id); //更新一本书 int updateBook(Books books); //查询一本书 Books queryBookById(@Param("bookID") int id); //查询全部的书 List<Books> queryAllBook(); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into ssmbuild.books (bookName, bookCounts, detail) values (#{bookName},#{bookCounts},#{detail}); </insert> <delete id="deleteBookById" parameterType="int"> delete from ssmbuild.books where bookID=#{bookId} </delete> <update id="updateBook" parameterType="Books"> update ssmbuild.books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}; </update> <select id="queryBookById" resultType="Books"> select * from ssmbuild.books where bookID=#{bookID} </select> <select id="queryAllBook" resultType="Books"> select * from ssmbuild.books </select> </mapper>
在mybatis核心配置文件中绑定mapper
<!--绑定mapper--> <mappers> <mapper class="com.kuang.dao.BookMapper"/> </mappers>
-
service层 BookService接口和BookServiceImpl
public interface BookService { //增加一本书 int addBook(Books books); //删除一本书 int deleteBookById(int id); //更新一本书 int updateBook(Books books); //查询一本书 Books queryBookById(int id); //查询全部的书 List<Books> queryAllBook(); }
public class BookServiceImpl implements BookService{ private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } //serice层调用dao层 public int addBook(Books books) { return bookMapper.addBook(books); } public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } public int updateBook(Books books) { return bookMapper.updateBook(books); } public Books queryBookById(int id) { return bookMapper.queryBookById(id); } public List<Books> queryAllBook() { return bookMapper.queryAllBook(); } }