Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.hibernate.LockMode;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- import org.hibernate.criterion.Restrictions;
- public class Hiber {
- public static void main(String[] args) {
- Configuration config = new Configuration();
- config.addAnnotatedClass(A.class);
- config.addAnnotatedClass(B.class);
- config.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
- config.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/heymoose");
- config.setProperty("hibernate.connection.username", "postgres");
- config.setProperty("hibernate.connection.password", "");
- config.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
- config.setProperty("hibernate.hbm2ddl.auto", "create-drop");
- config.setProperty("hibernate.show_sql", "true");
- config.setProperty("hibernate.format_sql", "false");
- config.setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
- config.setProperty("hibernate.current_session_context_class", "thread");
- config.setProperty("hibernate.jdbc.batch_size", "0");
- SessionFactory sessionFactory = config.buildSessionFactory();
- Integer id;
- Session session = sessionFactory.openSession();
- session.beginTransaction();
- A a = new A();
- B b = new B();
- b.setName("foo");
- a.setB(b);
- session.save(a);
- id = a.getId();
- session.getTransaction().commit();
- session.close();
- session = sessionFactory.openSession();
- session.beginTransaction();
- a = (A) session.get(A.class, id);
- b = a.getB();
- int bid = b.getId();
- session.evict(b);
- session.lock(b, LockMode.UPGRADE);
- b = (B) session.createCriteria(B.class).add(Restrictions.eq("id", bid)).list().get(0);
- b.setName("bar");
- sessionFactory.getCurrentSession();
- session.getTransaction().commit();
- session.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement