CREATE TABLE books(bid NUMBER PRIMARY KEY ,bname VARCHAR2(50) NOT NULL ,bprice NUMBER NOT NULL );
INSERT INTO books(bid,bname,bprice) VALUES (1,'百鬼夜行',12.5);
INSERT INTO books(bid,bname,bprice) VALUES (2,'陌上花开',22.5);
INSERT INTO books(bid,bname,bprice) VALUES (3,'夏目友人帐',32.5);
创建实体类
package edu.nf.mybatis.entity;
/**
* Created by Administrator on 2017/3/27.
*/
public class Books {
private long bid;
private String bname;
private double bprice;
public Books() {
}
public Books(long bid, String bname, double bprice) {
this.bid = bid;
this.bname = bname;
this.bprice = bprice;
}
public long getBid() {
return bid;
}
public void setBid(long bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public double getBprice() {
return bprice;
}
public void setBprice(double bprice) {
this.bprice = bprice;
}
@Override
public String toString() {
return "Books{" +
"bid=" + bid +
", bname='" + bname + '\'' +
", bprice=" + bprice +
'}';
}
}
View Code 定义访问接口
package edu.nf.mybatis.mapper;
import edu.nf.mybatis.entity.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by Administrator on 2017/3/27.
* 图书数据访问的接口
*/
public interface IBookDao {
/*获取所有书籍*/
public List<Books> getAll();
/*通过ID获取单个数据*/
public Books getBookById(@Param("bid") int bid);
/*添加数据*/
public int add(Books entity);
/*根据ID删除*/
public int del(int bid);
/*更新*/
public int update(Books entity);
}
View Code 创建xml映射文件定义实现数据访问需要的sql脚本
<?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="edu.nf.mybatis.mapper.IBookDao">
<!--id应该是对应接口的包名+接口名-->
<!--获取所有书籍-->
<!--因为在spring.xml文件中的sqlSessionFactory中配置属性 <property name="typeAliasesPackage" value="edu.nf.mybatis.entity"></property>-->
<!--所以这里resultType="Books"就只需要写类名Books,而不是edu.nf.mybatis.entity.Books了-->
<select id="getAll" resultType="Books">
select bid,bname,bprice from books
</select>
<!--通过编号获取书籍-->
<select id="getBookById" resultType="Books">
select bid,bname,bprice from books where bid = #{bid};
</select>
<!--添加书籍-->
<insert id="add">
insert into books(bid,bname,bprice) values (#{bid},#{bname},#{bprice});
</insert>
<!--删除书籍-->
<delete id="del">
delete from books where bid = #{bid};
</delete>
<!--更新书籍-->
<update id="update">
update books set bid = #{bid},bname = #{bname},bprice = #{bprice} where bid = #{bid};
</update>
</mapper>
View Code spring.xml完成整合,进行小测试