借助 BeanKeeper 快速实现对象持久化
2010-06-18 00:00:00 来源:WEB开发网package cn.ac.iscas.beankeeper.sample;
import java.util.Date;
public class EmployeeBean {
String id;
String name;
int age;
Date onBoardTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getOnBoardTime() {
return onBoardTime;
}
public void setOnBoardTime(Date onBoardTime) {
this.onBoardTime = onBoardTime;
}
}
接下来存储 EmployeeBean 对象到数据库中。首先从 CSV 文件中一条条读出员工信息,然后将这些信息生成一个 EmployeeBean 对象,最后将 EmployeeBean 对象持久化到数据库。
清单 2. 保存 EmployeeBean 对象代码
package cn.ac.iscas.beankeeper.sample;
import hu.netmind.persistence.Store;
import java.io.File;
import java.sql.Date;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class EmployeeSave {
private static Log log;
/**
* @param args
*/
public static void main(String[] args) {
System.setProperty("log4j.configuration", "file:log4j.xml");
log = LogFactory.getLog(EmployeeBean.class);
try {
String csvFile = args[0];
// open store, uses MySQL driver
Store store = new Store("org.gjt.mm.mysql.Driver",
"jdbc:mysql://localhost:3306/lhq?user=root&password=sa");
// read csv and generate beans
List historicalData = FileUtils.readLines(new File(csvFile));
// remove first line (header)
historicalData.remove(0);
// store beans to database
for (Object _data : historicalData) {
String[] data = ((String) _data).split(",");
EmployeeBean bean = new EmployeeBean();
bean.setId(data[0]);
bean.setName(data[1]);
bean.setAge(Integer.parseInt(data[2]));
bean.setOnBoardTime(Date.valueOf(data[3]));
// save stock bean to database
store.save(bean);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
system.out.println("Usage: java sample.StockData "
+ "<symbol name> <historical prices file> <query>");
}
}
}
Tags:借助 BeanKeeper 快速
编辑录入:爽爽 [复制链接] [打 印]更多精彩
赞助商链接