- 爱易网页
-
ASP.NET教程
- 三、现有的O/R Mapping产品介绍
日期:2012-04-09 浏览次数:20521 次
接上)
具体过程如下:
(1)首先建立数据库配置文件,我们在这里定为database.xml,当然也可以改成是其它名字。
<?xml version="1.0" encoding="gb2312"?>
<database name="CustomerDemo" engine="mysql">
<driver url="jdbc:mysql://cwb:3306/quickstart" class-name="org.gjt.mm.mysql.Driver">
<param name="user" value="dbusername"/>
<param name="password" value="dbpassword "/>
</driver>
<mapping href="Customer.xml"/>
</database>
建立影射文件Customer.xml
<?xml version="1.0" encoding="gb2312"?>
<class name="Demo.Customer" access="shared" identity="customerID">
<map-to table="users"/>
<field name="customerID" type="integer">
<sql name="customerID" type="integer"/>
</field>
<field name="name" type="string">
<sql name="name" type="varchar"/>
</field>
</class>
建立持久化类,与hibernate的是一样的类似javabean的类
package Demo;
public class Customer {
private String name;
private int customerID;
public Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
基本的实现后,我们可以看看这个demo怎么运行。
import java.util.*;
import org.exolab.castor.jdo.*;
import java.net.*;
public class CustomerManager {
JDO jdo;
Database db;
public CustomerManager() throws DatabaseNotFoundException,
PersistenceException {
//定义一个JDO对象
jdo = new JDO();
jdo.setDatabaseName("CustomerDemo");
jdo.setConfiguration("database.xml");
jdo.setClassLoader(getClass().getClassLoader());
//获得连接数据库
db = jdo.getDatabase();
}
/**
* 用于读取用户
* @param id Customer 对象的主键
*/
public Customer loadCustomer(Integer id) throws DatabaseNotFoundException,
PersistenceException {
Customer result = null;
//开始事务
db.begin();
result = (Customer) db.load(Customer.class, id);
//完成事务,关闭数据库
db.commit();
db.close();
return result;
}
/**
* 用于建立用户
* @param Customer newCustomer 新对象
*/
public void createCustomer(Customer newCustomer) throws
DatabaseNotFoundException,
PersistenceException {
Customer result = null;
db.begin();
//新建Customer
db.create(newCustomer);
db.commit();
db.close();
}
/**
* 更新旧的对象
*/
public Customer updateCustomer(Customer updateCustomer) throws
DatabaseNotFoundException,
PersistenceException {
db.begin();