java ee 实验 MyBatis 基于映射文件、基于接口和注解 对表增删改查

实习四 MyBatis
一、实习要求
1.掌握ORM概念及工作原理
2.掌握MyBatis的基本配置
3.掌握MyBatis的基本操作
4.了解MyBatis的高级查询
二、实习内容
创建一个表(books),包含字段:id(自动增长)、book_name(书名)、author(作者)、price(价格)、press(出版社)、press_date(出版日期)。
(1)基于映射文件(xml)完成对books的增删改查;
(2)基于接口及注解的增删改查
(3)使用动态SQL完成不确定项的查询,查询项包括除id之外的所有项,其中:书名、作者为模糊查询、价格、出版日期为范围查询。

三、实习过程

tip:所谓的id自动增长可以通过创建表定义列时设置,不过似乎不是所有数据库都支持,而本文是写了一个函数来获取最大id

工程结构:
在这里插入图片描述

主要代码:(所有代码可见工程目录)
Book.java

package entity;

public class Book {
    private Integer id;
    private String bookname;
    private String author;
    private Float price;
    private String press;
    private String pressdate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBookname() {
        return bookname;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getPress() {
        return press;
    }

    public void setPress(String press) {
        this.press = press;
    }

    public String getPressdate() {
        return pressdate;
    }

    public void setPressdate(String pressdate) {
        this.pressdate = pressdate;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookname='" + bookname + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", press='" + press + '\'' +
                ", pressdate='" + pressdate + '\'' +
                '}';
    }
}

BookMapper.java



package mappers;

import entity.Book;
import org.apache.ibatis.annotations.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public interface BookMapper {
   int getnewid();

   //基于配置文件
   List<HashMap<String,Object>> listAll();//查
   Book getById(Integer id);//查
   void add1( Map map);//增
   void delbyid1(Integer id);//删除
   void update1(Map map);//改

   List<Book> dynamicfind(Map map);//动态sql



   //基于注解
   @Select("select * from books where author = #{author}")
   Book getByAuthor(String author);//查

   @Insert("insert into books values (#{id}, #{bookname},#{author},#{price},#{press},#{pressdate})")
   void add2(@Param("id") int id , @Param("bookname") String bookname, @Param("author") String  author,
             @Param("price") Float price, @Param("press") String press, @Param("pressdate") String pressdate);//增


   @Update("update books set book_name=#{bookname}, author=#{author}, price=#{price}, press=#{press}, press_date=#{pressdate}\n" +
           "        where id=#{id}")
   void update2(@Param("id") int id , @Param("bookname") String bookname, @Param("author") String  author,
             @Param("price") Float price, @Param("press") String press, @Param("pressdate") String pressdate);//改


   @Delete("delete from books where id=#{id}")
   void delbyid2(int id);//删
}

Main.java


import entity.Book;
import mappers.BookMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String argc[]) throws IOException {
        InputStream is = Resources.getResourceAsStream("Mybatis-config.xml");
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = ssf.openSession();
        BookMapper mapper = session.getMapper(BookMapper.class);

        //基于配置文件
        //查
        List<HashMap<String,Object>> rs = mapper.listAll();
        System.out.println(rs.toString());

        Book r = mapper.getById(3);
        System.out.println(r.toString());

        //增
        Map map=new HashMap();
        map.put("id", mapper.getnewid()+1);
        map.put("bookname","大学英语");
        map.put("author","bb");
        map.put("price",Float.valueOf("18"));
        map.put("press","a出版社");
        map.put("pressdate","1999/2/2");
        //mapper.add1(map);

        //删
        //mapper.delbyid1(6);

        //改
        Map map1=new HashMap();
        map1.put("id", 7);
        map1.put("bookname","大学物理");
        map1.put("author","bb");
        map1.put("price",Float.valueOf("18"));
        map1.put("press","a出版社");
        map1.put("pressdate","1999/2/2");
        //mapper.update1(map1);


        //基于注解
        //查
        Book rr = mapper.getByAuthor("tom");
        System.out.println(rr.toString());
        //增
        //mapper.add2(10,"移动软件开发","李彬",Float.valueOf("29.5"),"西农出版社","2021/12/1");
        //改
        mapper.update2(10,"移动软件开发","李彬",Float.valueOf("139.5"),"西农出版社","2021/12/1");
        //删
        //mapper.delbyid2(10);

        //动态sql
        Map map2=new HashMap();
        //map2.put("bookname","大学");
        //map2.put("author","李");
        map2.put("price",Float.valueOf("10"));
        //map2.put("press","");
        List<Book> list1=mapper.dynamicfind(map2);
        for(Book book:list1)
        {
            System.out.println(book);
        }
        session.close();
    }
}

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="mappers.BookMapper">

    <select id="getnewid" resultType="int">
        select max(id)  from books
    </select>

    <select id="listAll" resultType="hashmap">
        select * from books
    </select>

    <select id="getById" parameterType="int" resultType="Book">
        select  * from books where id= #{id}
    </select>

    <select id="dynamicfind" parameterType="map" resultType="Book">
        select  * from books where 1=1
        <if test="bookname!=null and bookname!=''">and book_name like concat('%',#{bookname},'%')</if>
        <if test="author!=null and author!=''">and author like concat('%',#{author},'%')</if>
        <if test="price!=null and price!=''">and price between #{price}-10 and #{price}+10</if>
        <if test="press!=null and press!=''">and press like concat('%',#{press},'%') </if>

    </select>

    <insert id="add1" parameterType="map">
        insert into books values( #{id}, #{bookname}, #{author}, #{price}, #{press}, #{pressdate} )
    </insert>

    <delete id="delbyid1" parameterType="int">
        delete from books where id = #{id}
    </delete>

    <update id="update1" parameterType="map">
        update books set book_name=#{bookname}, author=#{author}, price=#{price}, press=#{press}, press_date=#{pressdate}
        where id=#{id}
    </update>


</mapper>

实验结果:
例如动态sql的结果:
查找书名包含“大学”并且价格在0到20:
在这里插入图片描述

结果:
在这里插入图片描述
其他的不放了

posted @ 2022-11-17 23:04  林动  阅读(85)  评论(0编辑  收藏  举报