Nonverbis

Untitled

Nov 17th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. @Override
  2. public boolean equals(Object o) {
  3. if (this == o) return true;
  4. if (!(o instanceof SimpleObject)) return false;
  5. SimpleObject that = (SimpleObject) o;
  6. // we prefer the method versions of accessors,
  7. // because of Hibernate's proxies.
  8. if (getId() != null ?
  9. !getId().equals(that.getId()) : that.getId() != null)
  10. return false;
  11. if (getKey() != null ?
  12. !getKey().equals(that.getKey()) : that.getKey() != null)
  13. return false;
  14. if (getValue() != null ?
  15. !getValue().equals(that.getValue()) : that.getValue() != null)
  16. return false;
  17. return true;
  18. }
  19. @Override
  20. public int hashCode() {
  21. int result = getId() != null ? getId().hashCode() : 0;
  22. result = 31 * result + (getKey() != null ? getKey().hashCode() : 0);
  23. result = 31 * result + (getValue() != null ? getValue().hashCode() : 0);
  24. return result;
  25. }
  26.  
  27.  
  28.  
  29. @Test
  30. public void testSaveLoad() {
  31. Long id = null;
  32. SimpleObject obj;
  33. try (Session session = SessionUtil.getSession()) {
  34. Transaction tx = session.beginTransaction();
  35. obj = new SimpleObject();
  36. obj.setKey("sl");
  37. obj.setValue(10 L);
  38. session.save(obj);
  39. assertNotNull(obj.getId());
  40. // we should have an id now, set by Session.save()
  41. id = obj.getId();
  42. tx.commit();
  43. }
  44. try (Session session = SessionUtil.getSession()) {
  45. // we're loading the object by id
  46. SimpleObject o2 = session.load(SimpleObject.class, id);
  47. assertEquals(o2.getKey(), "sl");
  48. assertNotNull(o2.getValue());
  49. assertEquals(o2.getValue().longValue(), 10 L);
  50. SimpleObject o3 = session.load(SimpleObject.class, id);
  51. // since o3 and o2 were loaded in the same session, they're not only
  52. // equivalent - as shown by equals() - but equal, as shown by ==.
  53. // since obj was NOT loaded in this session, it's equivalent but
  54. // not ==.
  55. assertEquals(o2, o3);
  56. assertEquals(obj, o2);
  57. assertTrue(o2 == o3);
  58. assertFalse(o2 == obj);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment