Hibernate创建和持久化Product
在向大家详细介绍持久化Product之前,首先让大家了解下Hibernate创建一个Product,然后全面介绍。
在我们假想的应用程序中,基本的使用模式非常简单:我们用Hibernate创建一个Product,然后将其持久化(或者换句话说,保存它);我们将搜索并加载一个已经持久化Product,并确保其可以使用;我们将会更新和删除Product。
Hibernate创建和持久化Product
现在我们终于用到Hibernate了。使用的场景非常简单:
1. Hibernate创建一个有效的Product。
2. 在应用程序启动时使用net.sf.Hibernate.cfg.Configuration获取net.sf.Hibernate.SessionFactory。
3. 通过调用SessionFactory#openSession(),打开net.sf.Hibernate.Session。
4. 保存Product,关闭Session。
正如我们所看到的,这里没有提到JDBC、SQL或任何类似的东西。非常令人振奋!下面的示例遵循了上面提到的步骤:
package test;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import test.hibernate.Product;
// 用法:
// java test.InsertProduct name amount price
public class InsertProduct {
public static void main(String[] args)
throws Exception {
// 1. 创建Product对象
Product p = new Product();
p.setName(args[0]);
p.setAmount(Integer.parseInt(args[1]));
p.setPrice(Double.parseDouble(args[2]));
// 2. 启动Hibernate
Configuration cfg = new Configuration()
.addClass(Product.class);
SessionFactory sf = cfg.buildSessionFactory();
// 3. 打开Session
Session sess = sf.openSession();
// 4. 保存Product,关闭Session
Transaction t = sess.beginTransaction();
sess.save(p);
t.commit();
sess.close();
}
} 当然,INFO行指出我们需要一个Hibernate.properties配置文件。在这个文件中,我们配置要使用的数据库、用户名和密码以及其他选项。使用下面提供的这个示例来连接前面提到的Hypersonic数据库:
hibernate.connection.username=sa hibernatehibernate.connection.password= hibernate.connection.url=jdbc:hsqldb:/home/davor/hibernate/orders hibernate.connection.driver_class=org.hsqldb.jdbcDriver hibernate.dialect=net.sf.hibernate.dialect.HSQLDialect