e)
{
this.id = value;
}
public String getId()
{
return id;
}
public void setName(String value)
{
this.name = value;
}
public String getName()
{
return name;
}
public void setAddress(String value)
{
this.address = value;
}
public String getAddress()
{
return address;
}
}
8、创建一个对象-关系映射的xml文件Person.hbm.xml,放在和Person.java相同的目录下面
<?xml version="1.0" encoding="GB2312"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<hibernate-mapping>
<class name="testhibernate.Person">
<!--hibernate为我们生成主键id-->
<id name = "id" unsaved-value = "null">
<generator class="uuid.hex"/>
</id>
<!--默认把类的变量映射为相同名字的表列,当然我们可以修改其映射方式-->
<property name="name"/>
<property name="address"/>
</class>
</hibernate-mapping>
9、创建调用类Person的客户端程序Client1.java
package testhibernate;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
/**
*本类只是用来创建表的,并不往表内部插入任何数据,并且只能使用一次,否则会删除已有的表的
*/
public class Client1
{
private static SessionFactory sessionFactory;
public static void main(String[] args) throws Exception
{
Configuration conf = new Configuration().addClass(Person.class);
//第一次运行时用来在数据库中创建表
//并且把sql语句输出到txt文件用的
//以后的运行不能使用该段代码,否则每次都会先删除原表,再新建该表
SchemaExport dbExport = new SchemaExport(conf);
dbExport.setOutputFile("sql.txt");
dbExport.create(true, true);
}
}
package testhibernate;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
public class Client2
{
private static SessionFactory sessionFactory;
public static void main(String[] args) throws Exception
{
Configuration conf = new Configuration().addClass(Person.class);
sessionFactory = conf.buildSessionFactory();
Session s = sessionFactory.openSession();
Transaction t = s.beginTransaction();
Person yuj = new Person();
yuj.setName("john");
yuj.setAddress("上海");
Person x = new Person();
x.setName("zhaoyh");
x.setAddress("上海");
//持久化
s.save(yuj); //此时yuj已经可以在数据库中找到
s.save(x); //此时x已经可以在数据库中找到
t.commit();
s.close();
}
}
查看数据库中,增加了2条记录,OK!初步使用成功了,剩下的慢慢研究吧…… |