Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory = new MetadataSources( serviceRegistry ).buildMetadata().buildSessionFactory();
// StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder()
// .applySettings(configuration.getProperties());
//
// StandardServiceRegistry registry = registryBuilder.build();
//
// sessionFactory = configuration.buildSessionFactory(registry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
1. 加载hibernate配置文件
2. 获取 SessionFactory
3. 获取 Session
其中在获取 SessionFactory 时按照示例程序的代码(注释区域)行不通,在 Stack Overflow 找到了解决办法,最终实现了。
tip:
User yawn = new User("yawn", "liu1234");
User yawn2 = yawn;
session.save(yawn);
session.save(yawn2);
最终保存的结果只有一条记录,yawn 和 yawn2 属于同一实例的不同引用,所以只对应数据库中一个元组。
User yawn = new User("yawn", "liu1234");
session.save(yawn);
yawn = new User("yawn2", "liu1234");
session.save(yawn);
保存结果又两条记录,两次yawn 分别是不同对象的引用。
User yawn = new User("yawn", "liu1234");
session.save(yawn);
yawn.setName("yawn2");
yawn.setPwd("1234yawn");
session.save(yawn);
保存结果只有一条记录。
hibernate的学习自今日开始,加油!