ibatis简单增删改查
下面是用ibatis做的一个简单的CRUD:
数据库:oracle中的DEPT表,
创建工程,导入ibatis的jar包.
在src根目录下创建sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
<property name="JDBC.Username" value="scott"/>
<property name="JDBC.Password" value="tiger"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/newer/pojo/Dept.xml"></sqlMap>
</sqlMapConfig>
创建DEPT表的POJO和映射文件:
Dept.java
public class Dept implements Serializable{
private static final long serialVersionUID = 1L;
private Integer deptno;
private String dname;
private String loc;
//属性对应的getter和setter方法
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
//默认无参构造方法
public Dept() {
}
Dept.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap>
<typeAlias alias="Dept" type="com.newer.pojo.Dept"/>
<!-- 根据ID查询 -->
<select id="findDeptById" parameterClass="int" resultClass="Dept">
SELECT DEPTNO as deptno,DNAME as dname,LOC as loc
FROM DEPT
WHERE DEPTNO=#deptno#
</select>
<!-- 查询全部 -->
<resultMap class="Dept" id="get-dept-result">
<result property="deptno" column="DEPTNO"/>
<result property="dname" column="DNAME"/>
<result property="loc" column="LOC"/>
</resultMap>
<select id="findAllDept" resultMap="get-dept-result">
SELECT * FROM DEPT
</select>
<!-- 添加 -->
<insert id="addDept" parameterClass="Dept">
INSERT INTO DEPT(DEPTNO,DNAME,LOC)
VALUES(#deptno#,#dname#,#loc#)
</insert>
<!-- 修改 -->
<update id="modifyDept" parameterClass="Dept">
UPDATE DEPT SET DNAME=#dname#,LOC=#loc#
WHERE DEPTNO=#deptno#
</update>
<!-- 删除 -->
<delete id="delDept" parameterClass="int">
DELETE FROM DEPT WHERE DEPTNO=#value#
</delete>
</sqlMap>
DeptDao.java
public class DeptDao {
private static SqlMapClient sqlMapClient;
static {
try {
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 根据编号查询
* @param deptno
* @return
*/
public Dept findDeptById(Integer deptno) {
Dept dept = null;
try {
dept=(Dept) sqlMapClient.queryForObject("findDeptById", deptno);
} catch (SQLException e) {
e.printStackTrace