在javaeye上看到Nutz,挺新鲜的一个东西,下面是试用的相关记录。
1、在数据库中创建相关的表:
CREATE TABLE tbl_test_person(
ID NUMBER(10) PRIMARY KEY,
NAME VARCHAR2(100),
remark VARCHAR2(1000)
);
2、编写相关json格式数据源配置文件datasource.json:
{
dataSource : {
type : "org.apache.commons.dbcp.BasicDataSource",
events : {
depose : 'close'
},
fields : {
driverClassName : 'oracle.jdbc.driver.OracleDriver',
url : 'jdbc:oracle:thin:@10.10.5.161:1521:oradb10',
username : 'fwmstest',
password : 'fwmstest'
}
}
}
3、编写相关的POJO:
package test;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Table;
@Table("tbl_test_person")
public class Person {
@Column
private int id;
@Column
private String name;
@Column
private String remark;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String toString() {
return "id:" + id + ",name:" + name + ",remark:" + remark;
}
}
4、配置相关的引用JAR:
ORACLE的驱动包classes12.zip
APACHE的commons-dbcp-1.3.jar包(最开始直接下载的是commons-dbcp-1.4.jar,但工程环境是1.5,所以运行的时候直接报java.lang.UnsupportedClassVersionError: Bad version number in .class file)以及相关的commons-pool-1.5.5.jar
log4j-1.2.16.jar
5、编写MAIN程序:
package test;
import java.util.List;
import org.apache.commons.dbcp.BasicDataSource;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.json.JsonLoader;
public class MainApp {
public static void main(String[] args) {
Ioc ioc = new NutIoc(new JsonLoader("test/datasource.json"));
BasicDataSource ds = ioc.get(BasicDataSource.class, "dataSource");
Dao dao = new NutDao(ds);
// 插入10条数据
for (int i = 0; i < 10; i++) {
Person p = new Person();
p.setId(i + 1);
p.setName("good" + i);
p.setRemark("remark" + i);
dao.insert(p);
}
// 查询所有记录
List<Person> list = dao.query(Person.class, null, null);
for (Person p : list) {
System.out.println(p);
}
}
}
6、程序运行结果如下:
控制台的输出:
2010-10-14 12:59:56 WARN [main] !!You are using default SystemLog! Don't use it in Production environment!!
id:1,name:good0,remark:remark0
id:2,name:good1,remark:remark1
id:3,name:good2,remark:remark2
id:4,name:good3,remark:remark3
id:5,name:good4,remark:remark4
id:6,name:good5,remark:remark5
id:7,name:good6,remark:remark6
id:8,name:good7,remark:remark7
id:9,name:good8,remark:remark8
id:10,name:good9,remark:remark9
数据库中,执行查询语句,也对上了号。