SlideShare a Scribd company logo
@jkubrynski / kubrynski.com
JPA - BEYOND COPY-PASTE
JAKUB KUBRYNSKI
jk@devskiller.com / @jkubrynski / http://kubrynski.com
WHOAMI
CO-FOUNDER OF DEVSKILLER / CODEARTE
TRAINER AT BOTTEGA
DEVOXX.PL PROGRAM COMMITTEE
FORMER CONFITURA.PL
JPA - Beyond copy-paste
@Entity
public class Product {
    @Id
    @GeneratedValue 
    private Long id; 
    @Column
    private String name; 
    // ...
}
@Entity
public class Product {
    @Id
    @GeneratedValue 
    private Long id; 
    @Column // it does exactly nothing 
    private String name; 
    // ...
}
@Transactional @Service 
public class ProductService { 
    public void updatePrice(Long productId, Money newPrice) { 
        Product product = productRepository.find(productId); 
        product.setPrice(newPrice); 
        productRepository.save(product); 
    }
}
@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 
    }
}
FIELDS VS GETTERS
@Entity
public class Product {
    private Long id; 
    private String name; 
    @Id
    public Long getId() {
        return id; 
    }
}
MIXED ACCESS
@Entity
@Access(AccessType.FIELD) 
public class Product {
    private Long id; 
    private String name; 
    @Id
    @Access(AccessType.PROPERTY) 
    public Long getId() {
        return id; 
    }
}
@Entity
public class Order {
}
@Entity(name = "orders") 
public class Order {
}
@Entity(name = "orders") 
public class Order {
}
insert into orders ... 
@Entity(name = "orders") 
public class Order {
}
em.createQuery("SELECT o FROM Order o") 
@Entity(name = "orders") 
public class Order {
}
em.createQuery("SELECT o FROM orders o") 
@Entity
@Table(name = "orders") 
public class Order {
}
ONE TO ONE
@Entity
public class Customer { 
    @OneToOne 
    private Address address; 
}
@Entity
public class Address {
    @OneToOne 
    private Customer customer; 
}
ONE TO ONE
@Entity
public class Customer { 
    @OneToOne 
    private Address address; 
}
@Entity
public class Address {
    @OneToOne(mappedBy = "address") 
    private Customer customer; 
}
ONE TO MANY
@Entity
public class Customer { 
    @OneToMany 
    private Set<Address> addresses; 
}
ONE TO MANY
@Entity
public class Customer { 
    @OneToMany 
    @JoinColumn(name = "customer_id") 
    private Set<Address> addresses; 
}
MANY TO MANY
@Entity
public class Customer { 
    @ManyToMany 
    private Collection<Address> addresses; 
}
@Entity
public class Address {
    @ManyToMany 
    private Collection<Customer> customers; 
}
LAZY LOADING
element is loaded only when required
proxy by subclassing, but not always needed
LAZY LOADING
Custom collections
PersistentSet
PersistentBag
PersistentList
SET, BAG OR LIST?
@OneToMany 
Set<Product> products; 
SET, BAG OR LIST?
@OneToMany 
List<Product> products; 
SET, BAG OR LIST?
@OneToMany 
@OrderColumn 
List<Product> products; 
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()) { 
        ... 
    }
}
N+1
@Entity
public class User {
    @OneToMany 
    @BatchSize(size = 10) 
    private List<Address> addresses; 
}
N+1
SELECT DISTINCT u FROM User u 
    JOIN FETCH u.addresses 
HOW TO SAVE
EntityManager.persist()
EntityManager.merge()
OPTIMISTIC LOCKING
@Entity
public class User {
   @Version 
   private int version; 
}
OPTIMISTIC LOCKING IN REST
NEVER HEARD OF IT
IDENTITY
EQUALS() AND HASHCODE()
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); 
     }
}
CACHING
L1 - EntityManager cache / Session cache
L2 - EntityManagerFactory cache / SessionFactory cache
QueryCache
FLUSH MODES
MANUAL
COMMIT
AUTO
ALWAYS
LEVEL 1 CACHE PITFALLS
FLUSH() AND CLEAR()
LEVEL 2 CACHE PITFALLS
DISTRIBUTED ENVIRONMENT
HQL INJECTION
String hqlQuery = "SELECT p FROM Product p where p.category = '" + cat + "'"; 
List<Product> products = em.createQuery(hqlQuery, Product.class) 
                           .getResultList(); 
DYNAMIC UPDATES
@Entity
@DynamicUpdate 
public class MyEntity { 
// ...
}
DYNAMIC INSERTS
@Entity
@DynamicInsert 
public class MyEntity { 
// ...
}
QUESTIONS?
THANKS

More Related Content

PDF
JVM Dive for mere mortals
PDF
API management with Taffy and API Blueprint
PDF
Gradle in a Polyglot World
PDF
Kotlin - Better Java
PPT
Symfony2 Service Container: Inject me, my friend
PPT
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
PDF
Using the Groovy Ecosystem for Rapid JVM Development
PDF
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
JVM Dive for mere mortals
API management with Taffy and API Blueprint
Gradle in a Polyglot World
Kotlin - Better Java
Symfony2 Service Container: Inject me, my friend
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
Using the Groovy Ecosystem for Rapid JVM Development
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014

What's hot (20)

PDF
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
PDF
Mobile Open Day: React Native: Crossplatform fast dive
PDF
Deep Dive Java 17 Devoxx UK
PPT
GWT Extreme!
PDF
Gradle in 45min
PPT
Groovy & Grails: Scripting for Modern Web Applications
PPT
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
PDF
Android antipatterns
ZIP
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
PPTX
Going native with less coupling: Dependency Injection in C++
PDF
Doctrine ORM with eZ Platform REST API and GraphQL
PDF
Kotlin intro
PDF
A Taste of Clojure
PDF
JAX-RS and CDI Bike the (Reactive) Bridge
PPTX
ABCs of docker
PPTX
Angular beans
KEY
CoffeeScript By Example
PDF
Apache Groovy: the language and the ecosystem
KEY
groovy & grails - lecture 6
PPTX
When Enterprise Java Micro Profile meets Angular
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Mobile Open Day: React Native: Crossplatform fast dive
Deep Dive Java 17 Devoxx UK
GWT Extreme!
Gradle in 45min
Groovy & Grails: Scripting for Modern Web Applications
JavaOne 2008 - TS-5793 - Groovy and Grails, changing the landscape of Java EE...
Android antipatterns
Groovy and Grails in Action - Devoxx 2008 - University - Guillaume Laforge
Going native with less coupling: Dependency Injection in C++
Doctrine ORM with eZ Platform REST API and GraphQL
Kotlin intro
A Taste of Clojure
JAX-RS and CDI Bike the (Reactive) Bridge
ABCs of docker
Angular beans
CoffeeScript By Example
Apache Groovy: the language and the ecosystem
groovy & grails - lecture 6
When Enterprise Java Micro Profile meets Angular
Ad

Similar to JPA - Beyond copy-paste (20)

PDF
JDD 2016 - Jakub Kubrynski - Jpa - beyond copy-paste
ODP
Java Persistence API
PDF
Java persistence api 2.1
PDF
Kick Start Jpa
PDF
Understanding
PDF
Using the latest Java Persistence API 2.0 features
PPTX
PPT
PPTX
Codecamp iasi-26 nov 2011-what's new in jpa 2.0
ODP
Jpa buenas practicas
ODP
JPA Best Practices
PPT
test for jpa spring boot persistence hehe
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
PPT
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
PDF
ActiveJDBC - ActiveRecord implementation in Java
PDF
PDF
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
PPT
03 Object Relational Mapping
PPTX
HIBERNATE For Databases java presentation.pptx
PPT
Spring data
JDD 2016 - Jakub Kubrynski - Jpa - beyond copy-paste
Java Persistence API
Java persistence api 2.1
Kick Start Jpa
Understanding
Using the latest Java Persistence API 2.0 features
Codecamp iasi-26 nov 2011-what's new in jpa 2.0
Jpa buenas practicas
JPA Best Practices
test for jpa spring boot persistence hehe
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
ActiveJDBC - ActiveRecord implementation in Java
PostgreSQL - масштабирование в моде, Valentine Gogichashvili (Zalando SE)
03 Object Relational Mapping
HIBERNATE For Databases java presentation.pptx
Spring data
Ad

More from Jakub Kubrynski (14)

PDF
Work sample coding tests
PDF
6 key tips for conducting an effective skill assessment interview
PDF
-XX:+UseG1GC
PDF
Consumer Driven Contracts - 4Developers 2015
PDF
REST - the good and the bad parts
PDF
REST - the good and the bad parts
PDF
What you won't read in books about RESTful services
PDF
Introduction to Spring Boot!
PDF
Warsjawa profiling tools
PDF
Warsjawa profiling
PDF
JOOX - Java Object Oriented XML
PDF
Arquillian
PDF
Spring Data
PDF
Profiling
Work sample coding tests
6 key tips for conducting an effective skill assessment interview
-XX:+UseG1GC
Consumer Driven Contracts - 4Developers 2015
REST - the good and the bad parts
REST - the good and the bad parts
What you won't read in books about RESTful services
Introduction to Spring Boot!
Warsjawa profiling tools
Warsjawa profiling
JOOX - Java Object Oriented XML
Arquillian
Spring Data
Profiling

Recently uploaded (20)

PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPT
Introduction Database Management System for Course Database
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Digital Strategies for Manufacturing Companies
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administration Chapter 2
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Introduction to Artificial Intelligence
PDF
Nekopoi APK 2025 free lastest update
PPTX
ai tools demonstartion for schools and inter college
PDF
AI in Product Development-omnex systems
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Online Work Permit System for Fast Permit Processing
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Introduction Database Management System for Course Database
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Digital Strategies for Manufacturing Companies
Upgrade and Innovation Strategies for SAP ERP Customers
Operating system designcfffgfgggggggvggggggggg
Softaken Excel to vCard Converter Software.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administration Chapter 2
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Introduction to Artificial Intelligence
Nekopoi APK 2025 free lastest update
ai tools demonstartion for schools and inter college
AI in Product Development-omnex systems
CHAPTER 2 - PM Management and IT Context
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Odoo POS Development Services by CandidRoot Solutions
Online Work Permit System for Fast Permit Processing

JPA - Beyond copy-paste