二、Mybatis层
1、连接数据库
1.1创建database.properties
我用的是mysql8.0,连接出错的话需要增加一个时区的配置&serverTimezone=Asia/Tianjin
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/wmmbooks?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&allowPublicKeyRetrieval=true user=root password=123456
2、创建实体类
package com.hxl.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
记得导入lombok的包
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
3、接口
package com.hxl.dao; import com.hxl.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookMapper { //增加 int addBook(Books books); //删除 int deleteBookById(@Param("bookId")int id); //更新 int updateBook(Books books); //查询一本书 Books queryBookById(int id); //查询全部的书 List<Books> queryAllBook(); }
BookMapper.xml
<?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.hxl.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into wmmbooks.books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail}) </insert> <!--这里写int是Integer,写_int才是int。但是java里可以转换,自动拆箱和装箱--> <!--这里写bookId是因为在接口中使用了@Param这个注解,否则需要写id--> <delete id="deleteBookById" parameterType="int"> delete from wmmbooks.books where bookID = #{bookId} </delete> <update id="updateBook" parameterType="Books"> update wmmbooks.books set bookName = #{bookName}, bookCounts=#{bookCounts},detail=#{detail} where bookID = #{bookID} </update> <select id="queryBookById" parameterType="Books"> select * from wmmbooks.books where bookID = #{bookID} </select> <select id="queryAllBook" parameterType="Books"> select * from wmmbooks.books </select> </mapper>
写完就需要立马绑定到mybatis配置文件中
<mappers> <mapper class="com.hxl.dao.BookMapper"/> </mappers>
4、业务层
BookService
package com.hxl.service; import com.hxl.pojo.Books; import java.util.List; public interface BookService { //增加 int addBook(Books books); //删除 int deleteBookById(int id); //更新 int updateBook(Books books); //查询一本书 Books queryBookById(int id); //查询全部的书 List<Books> queryAllBook(); }
写完去写它的实现类BookServiceImpl