Hibernate Component映射的一个简单例子(二)

2014-11-24 11:17:27 · 作者: · 浏览: 2
[java]
package collect.component;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
// Configuration管理Hibernate配置
Configuration config = new Configuration().configure();
// 根据Configuration建立 SessionFactory
// SessionFactory用来建立Session
SessionFactory sessionFactory = config.buildSessionFactory();
// 创建实例
Name name=new Name();
name.setFirstname("闫");
name.setLastname("术卓");
Contact contact = new Contact();
contact.setAddress("北京");
contact.setTel("42689334");
contact.setZipcodes("100085");
Cuser user= new Cuser();
user.setAge(33);
user.setName(name);
user.setContact(contact);
// 定义主键变量
Integer pid;
// 添加数据
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// 创建主键变量
pid = (Integer) session.save(user);
tx.commit();
} catch (RuntimeException e) {
if (tx != null)
tx.rollback();
throw e;
} finally {
session.close();
}
// 关闭sessionFactory
sessionFactory.close();
}
}
运行结果:
控制台:
20:47:57,366 DEBUG SQL:346 - insert intossh.c_user (age, firstname, lastname, address, zipcode, tel) values ( , , , , , )
数据库