- 创建一个有效的Product。
- 在应用程序启动时使用net.sf.hibernate.cfg.Configuration获取net.sf.hibernate.SessionFactory。
- 通过调用SessionFactory#openSession(),打开net.sf.hibernate.Session。
- 保存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()上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] ... 下一页 >>
|