Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JPA - Beyond Copy-Paste

JPA - Beyond Copy-Paste

Jakub Kubryński

May 19, 2017
Tweet

More Decks by Jakub Kubryński

Other Decks in Programming

Transcript

  1. @Entity public class Product { @Id @GeneratedValue private Long id;

    @Column // it does exactly nothing private String name; // ... }
  2. @Transactional @Service public class ProductService { public void updatePrice(Long productId,

    Money newPrice) { Product product = productRepository.find(productId); product.setPrice(newPrice); productRepository.save(product); } }
  3. @Transactional @Service public class ProductService { public void updatePrice(Long productId,

    Money newPrice) { Product product = productRepository.find(productId); product.setPrice(newPrice); productRepository.save(product); // it does exactly nothing } }
  4. FIELDS VS GETTERS @Entity public class Product { private Long

    id; private String name; @Id public Long getId() { return id; } }
  5. MIXED ACCESS @Entity @Access(AccessType.FIELD) public class Product { private Long

    id; private String name; @Id @Access(AccessType.PROPERTY) public Long getId() { return id; } }
  6. ONE TO ONE @Entity public class Customer { @OneToOne private

    Address address; } @Entity public class Address { @OneToOne private Customer customer; }
  7. ONE TO ONE @Entity public class Customer { @OneToOne private

    Address address; } @Entity public class Address { @OneToOne(mappedBy = "address") private Customer customer; }
  8. ONE TO MANY @Entity public class Customer { @OneToMany @JoinColumn(name

    = "customer_id") private Set<Address> addresses; }
  9. MANY TO MANY @Entity public class Customer { @ManyToMany private

    Collection<Address> addresses; } @Entity public class Address { @ManyToMany private Collection<Customer> customers; }
  10. N+1 @Entity public class User { @OneToMany private List<Address> addresses;

    } List<User> users = em.createQuery("SELECT u FROM User u").getResultList(); for (User user : users) { for (Address address : user.getAddresses()) { ... } }
  11. BASE CLASS @MappedSuperclass public abstract class BaseEntity implements Serializable {

    @Id @GeneratedValue private Long id; private String uuid = UUID.randomUUID().toString(); public int hashCode() { return Objects.hash(uuid); } public boolean equals(Object that) { return this == that || that instanceof BaseEntity && Objects.equals(uuid, ((BaseEntity) that).uuid); }
  12. CACHING L1 - EntityManager cache / Session cache L2 -

    EntityManagerFactory cache / SessionFactory cache QueryCache
  13. HQL INJECTION String hqlQuery = "SELECT p FROM Product p

    where p.category = '" + cat + "'"; List<Product> products = em.createQuery(hqlQuery, Product.class) .getResultList();