mybatis的xml對映檔案,dao介面類,entity實體類
阿新 • • 發佈:2019-01-03
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">
Book實體類(成員變數與資料庫的一張表的屬性一一對應):
package com.cm.entity;
import java.util.Date;
import com.mysql.cj.xdevapi.Result;
/**
* 圖書實體
*/
public class Book {
/**
* 編號
*/
private int id;
/**
* 書名
*/
private String title;
/**
* 價格
*/
private double price;
/**
* 出版日期
*/
private Date publishDate;
public Book(int id, String title, double price, Date publishDate) {
this .id = id;
this.title = title;
this.price = price;
this.publishDate = publishDate;
}
public Book() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public String toString() {
String result = "id:" + id
+ " title:" + title
+ " price:" + price
+ " publishDate:" + publishDate;
return result;
}
}
BookDAO介面(定義了對Book所對應的表的各種操作,但沒有實現):
package com.cm.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.cm.entity.Book;
/**
* 圖書資料訪問介面
*/
public interface BookDAO {
/**
* 獲得所有圖書
*/
public List<Book> getAllBooks();
/**
* 根據圖書編號獲得圖書物件
*/
public Book getBookById(@Param("id") int id);
/**
* 新增圖書
*/
public int add(Book entity);
/**
* 根據圖書編號刪除圖書
*/
public int delete(int id);
/**
* 更新圖書
*/
public int update(Book entity);
}
BookMapper.xml例項(用sql語句實現dao介面的方法):
<?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.cm.dao.BookDAO">
<select id="getAllBooks" resultType="com.cm.entity.Book">
select id, title, price, publishDate from books
</select>
<select id="getBookById">
select id, title, price, publishDate from books where id=#{id}
</select>
<insert id="add">
insert into books(title,price,publishDate)
values(#{title},#{price},#{publishDate})
</insert>
<delete id="delete">
delete from books where id=#{id}
</delete>
<update id="update">
update books set title=#{title},price=#{price},publishDate=#{publishDate}
where id=#{id}
</update>
</mapper>
<mapper namespace = “dao介面完整的包名和介面名”>
<select>用於sql查詢語句
<insert>用於sql新增語句
<update>用於sql更新語句
<delete>用於sql刪除語句