Posted on 2009-10-19 13:14
H2O 阅读(1260)
评论(0) 编辑 收藏 所属分类:
DataBase
1.来一个Person类
package com.Jdnis.ibatis.model;
import java.io.Serializable;
import java.sql.Date;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int id ;
private String firstName ;
private String lastName ;
private Date birthDate = new Date(1900,1,1);;
private double weight ;
private double height ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
2.oop编程中,面向接口编程是一种很好的编程风格。在这一步骤中,定义Person实例的一个操作接口:
package com.Jdnis.ibatis.interfaces;
import java.util.List;
import com.ibatis.dao.client.Dao;
import com.Jdnis.ibatis.model.Person;
public interface PersonInterface extends Dao{
public void insertPerson(Person p);
public void updatePerson(Person p);
public List selectAllPerson( );
}
3.对接口的实现类
package com.Jdnis.ibatis.interfaces;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.template.SqlMapDaoTemplate;
import com.Jdnis.ibatis.model.Person;
public class PersonImpl extends SqlMapDaoTemplate implements PersonInterface {
public PersonImpl(DaoManager daoManager) {
super(daoManager);
// TODO Auto-generated constructor stub
}
public void insertPerson(Person p) {
// TODO Auto-generated method stub
try {
this.getSqlMapExecutor().insert("insertPerson",p);
System.out.println("数据插入成功!");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("插入出错,主键冲突!");
}
}
public void updatePerson(Person p) {
// TODO Auto-generated method stub
try {
this.getSqlMapExecutor().update("updatePerson",p);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List selectAllPerson() {
// TODO Auto-generated method stub
return queryForList("selectAllPerson",null);
}
}
4.配置person.xml文件:实现对象与数据库的映射
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">
<!-- 缓存 -->
<typeAlias alias="person" type="com.Jdnis.ibatis.model.Person" />
<parameterMap id="insert_person" class="person">
<parameter property="id" jdbcType="int" />
<parameter property="firstName" jdbcType="varchar"/>
<parameter property="lastName" jdbcType="varchar"/>
<parameter property="birthDate" jdbcType="Date"/>
<parameter property="weight" jdbcType="double" />
<parameter property="height" jdbcType="double" />
</parameterMap>
<resultMap id="allPersons" class="person">
<result property="id" column="per_id" />
<result property="firstName" column="per_first_name" />
<result property="lastName" column="per_last_name" />
<result property="birthDate" column="per_birth_date" />
<result property="weight" column="weightInKilograms" />
<result property="height" column="heightInMeters" />
</resultMap>
<statement id="insertPerson" parameterMap="insert_person">
INSERT INTO persons VALUES(?,?,?,?,?,?)
</statement>
<statement id="selectAllPerson" resultMap="allPersons">
<![CDATA[select * from persons]]>
</statement>
<statement id="updatePerson" parameterClass="person">
<![CDATA[update persons set per_first_name=#firstName#,per_last_Name=#lastName#,per_birth_date=#birthDate#,weightInKilograms=#weight#,heightInMeters=#height# where per_id=#id#]]>
</statement>
</sqlMap>
5.SqlMapConfig.xml文件的配置:配置数据源
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- 地方i -->
<settings cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
errorTracingEnabled="true"
maxRequests="32"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost/person" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="root" />
<property name="Pool.MaximumActiveConnections" value="10" />
<property name="Pool.MaximumIdleConnections" value="5" />
<property name="Pool.MaximumCheckoutTime" value="120000" />
<property name="Pool.TimeToWait" value="500" />
<property name="Pool.PingQuery" value="select 1 from sample" />
<property name="Pool.PingEnabled" value="false" />
<property name="Pool.PingConnectionsOlderThan" value="1" />
<property name="Pool.PingConnectionsNotUsedFor" value="1" />
</dataSource>
</transactionManager>
<sqlMap resource="com/Jdnis/ibatis/map/person.xml" />
</sqlMapConfig>
6.ibatis的dao.xml文件的配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE daoConfig PUBLIC "-//ibatis.apache.org//DTD DAO Configuration 2.0//EN" "http://ibatis.apache.org/dtd/dao-2.dtd">
<daoConfig>
<context>
<transactionManager type="SQLMAP">
<property name="SqlMapConfigResource" value="com/neusoft/ibatis/map/SqlMapConfig.xml" />
</transactionManager>
<dao interface="com.neusoft.ibatis.interfaces.PersonInterface" implementation="com.Jdnis.ibatis.interfaces.PersonImpl" />
</context>
</daoConfig>
该文件的<transactionManager>元素将刚才的SqlMapConfig.xml相关联起来,使得三个配置文件都联系到了一起,<
dao>元素的配置是将
dao接口与其实现类关联起来。
7.dao.xml文件的解析
package com.Jdnis.ibatis.dao;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
import com.ibatis.common.resources.Resources;
import com.ibatis.dao.client.DaoManager;
import com.ibatis.dao.client.DaoManagerBuilder;
public class DAOConfig {
private static final String resource="com/Jdnis/ibatis/map/dao.xml";
private static final DaoManager daoManager;
static{
daoManager = newDaoManager(null);
}
public static DaoManager getDaoManager(){
return daoManager;
}
public static DaoManager newDaoManager(Properties props){
try {
Reader reader = Resources.getResourceAsReader(resource);
return DaoManagerBuilder.buildDaoManager(reader,props);
} catch (Exception e) {
// TODO Auto-generated catch block
new RuntimeException("Could not initialize DaoConfig. Cause: " + e, e);
}
return null;
}
}
8.测试类
package com.Jdnis.ibatis.dao;
import java.sql.Date;
import com.ibatis.dao.client.DaoManager;
import com.Jdnis.ibatis.interfaces.PersonInterface;
import com.Jdnis.ibatis.model.Person;
public class TestCase {
DaoManager daoManager;
protected void setUp()throws Exception{
daoManager = DAOConfig.getDaoManager();
}
public void testInsertPerson(){
PersonInterface pi = (PersonInterface)daoManager.getDao(PersonInterface.class);
Person p = new Person();
p.setId(2);
p.setFirstName("firstName");
p.setLastName("lastName");
//p.setBirthDate(new Date(21,12,25));
p.setHeight(172);
p.setWeight(125);
pi.insertPerson(p);
}
public static void main(String[] args){
TestCase tc = new TestCase();
try {
tc.setUp();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tc.testInsertPerson();
}
}
ibatis通过
PersonInterface pi = (PersonInterface)daoManager.getDao(PersonInterface.class);
这种反射的机制,来实例化一个接口的实现类(
dao.xml文件中接口与实现类的关联)