Advertisement
Guest User

Untitled

a guest
Oct 6th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import org.hibernate.LockMode;
  2. import org.hibernate.Session;
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5. import org.hibernate.criterion.Restrictions;
  6.  
  7. public class Hiber {
  8.  
  9.  
  10. public static void main(String[] args) {
  11. Configuration config = new Configuration();
  12.  
  13. config.addAnnotatedClass(A.class);
  14. config.addAnnotatedClass(B.class);
  15.  
  16. config.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
  17. config.setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/heymoose");
  18. config.setProperty("hibernate.connection.username", "postgres");
  19. config.setProperty("hibernate.connection.password", "");
  20. config.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
  21. config.setProperty("hibernate.hbm2ddl.auto", "create-drop");
  22. config.setProperty("hibernate.show_sql", "true");
  23. config.setProperty("hibernate.format_sql", "false");
  24. config.setProperty("hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory");
  25. config.setProperty("hibernate.current_session_context_class", "thread");
  26. config.setProperty("hibernate.jdbc.batch_size", "0");
  27.  
  28. SessionFactory sessionFactory = config.buildSessionFactory();
  29.  
  30. Integer id;
  31.  
  32. Session session = sessionFactory.openSession();
  33. session.beginTransaction();
  34.  
  35. A a = new A();
  36. B b = new B();
  37. b.setName("foo");
  38. a.setB(b);
  39. session.save(a);
  40. id = a.getId();
  41.  
  42. session.getTransaction().commit();
  43. session.close();
  44.  
  45. session = sessionFactory.openSession();
  46. session.beginTransaction();
  47.  
  48. a = (A) session.get(A.class, id);
  49. b = a.getB();
  50. int bid = b.getId();
  51. session.evict(b);
  52. session.lock(b, LockMode.UPGRADE);
  53. b = (B) session.createCriteria(B.class).add(Restrictions.eq("id", bid)).list().get(0);
  54. b.setName("bar");
  55.  
  56. sessionFactory.getCurrentSession();
  57.  
  58. session.getTransaction().commit();
  59. session.close();
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement