接口:

public interface BookMapper {
    // 创建图书
    int createBook(Book book);
    // 根据ID获取图书信息
    Book getBookById(int id);
    // 获取所有图书信息
    List<Book> getAllBooks();
    // 更新图书信息
    int updateBook(Book book);
    // 删除图书
    int deleteBook(int id);
}

Book实体类:

public class Book {
    private int id;
    private String name;
    private String author;
    private String publisher;
    private Date publishDate;
    private double price;
    
    // getter和setter方法
}

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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/bookdb" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="mybatis/BookMapper.xml"/>
    </mappers>
</configuration>

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">
    <resultMap id="bookResultMap" type="com.example.entity.Book">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="author" column="author" />
        <result property="publisher" column="publisher" />
        <result property="publishDate" column="publish_date" />
        <result property="price" column="price" />
    </resultMap>

    <insert id="createBook" parameterType="com.example.entity.Book" useGeneratedKeys="true" keyProperty="id">
        insert into book(name, author, publisher, publish_date, price)
        values (#{name}, #{author}, #{publisher}, #{publishDate}, #{price})
    </insert>

    <select id="getBookById" parameterType="int" resultMap="bookResultMap">
        select * from book where id = #{id}
    </select>

    <select id="getAllBooks" resultMap="bookResultMap">
        select * from book
    </select>

    <update id="updateBook" parameterType="com.example.entity.Book">
        update book set name=#{name}, author=#{author}, publisher=#{publisher}, publish_date=#{publishDate}, price=#{price} where id=#{id}
    </update>

    <delete id="deleteBook" parameterType="int">
        delete from book where id=#{id}
    </delete>
</mapper>
写一个查询图书信息的数据库CRUD接口并生成一个mybatis的配置文件

原文地址: https://www.cveoy.top/t/topic/gNu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录