SlideShare a Scribd company logo
1 of 17
Download to read offline
Spring JPA
技术分享
2019-09
Entity及其关系2
N+1问题及其解决方案3
JPA简介1
JPA简介1
基本概念
• JPA(Java Persistence API)
• Hibernate
• Spring Data JPA
Entity的生命周期
EntityManager
Java Object Record
EntityManager
Create
Retrieve
Update
Delete
persist()
find()
merge(),flush()
remove()
Entity及其关系2
Entity及其关系
关系:
• 一对一
• 一对多
• 多对多
关系类型:
• 单向
• 双向
代码表示
注释类型:
• @OneToOne
• @ManyToOne
• @OneToMany
• @ManyToMany
@Entity
@Table(name = "`database`")
public class Database {
private Long id;
private Cluster cluster;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "`id`")
public Long getId() {
return id;
}
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "`cluster_id`", nullable = false)
public Cluster getCluster() {
return cluster;
}
}
注释属性的作用
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface OneToMany {
Class targetEntity() default void.class;
CascadeType[] cascade() default {};
FetchType fetch() default LAZY;
String mappedBy() default "";
boolean orphanRemoval() default false;
}
3 N+1问题及其解决方案
N+1问题
在查询Cluster时,查到n条结果,
每个结果还会附加一次Database
查询。
@Entity
@Table(name = "`cluster`")
public class Cluster {
private Long id;
private List<Database> databases;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "`id`")
public Long getId() {
return id;
}
@OneToMany(fetch = FetchType.EAGER,
mappedBy = "`database_id`")
public List<Database> getDatabase() {
return databases;
}
}
select * from cluster;
+
select * from database where cluster_id = ?
select * from database where cluster_id = ?
…
解决方案
1. 使用懒加载,用到
database的时候再去
查询。
@Entity
@Table(name = "`cluster`")
public class Cluster {
private Long id;
private List<Database> databases;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "`id`")
public Long getId() {
return id;
}
@OneToMany(fetch = FetchType.LAZY , mappedBy = "`database_id`")
public List<Database> getDatabase() {
return databases;
}
}
解决方案
2. 使用Join的方式
public interface ClusterRepository extends CrudRepository<Cluster,Long> {
@Override
@Query(value = "select * from cluster left outer join database
on id = database.cluster_id", nativeQuery = true)
Iterable<Cluster> findAll();
}
解决方案
3. 使用Join的方式(EntityGraph)
@Entity
@Table(name = "`cluster`")
@NamedEntityGraph(name = “cluster-entity-graph",
attributeNodes = {@NamedAttributeNode(“databases")})
public class Cluster {
private Long id;
private List<Database> databases;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "`id`")
public Long getId() {
return id;
}
@OneToMany(fetch = FetchType.LAZY , mappedBy
="`database_id`")
public List<Database> getDatabase() {
return databases;
}
}
select * from cluster left outer join database
on id = database.cluster_id
public interface ClusterRepository extends
CrudRepository<Cluster, Integer> {
@Override
@EntityGraph("cluster-entity-graph")
Iterable<Cluster> findAll();
}
EntityGraph的好处
可以在运行时调整取用实体的方式,更加灵活。
EntityGraph entityGraph = entityManager.getEntityGraph("user-entity-graph");
Map<String, Object> properties = new HashMap<>();
properties.put("javax.persistence.fetchgraph", entityGraph);
entityManager.find(User.class, 1,properties);
entityManager.find(User.class, 1,properties); Lazy方式
Join方式
Spring jpa share

More Related Content

Similar to Spring jpa share

Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1Shinichi Ogawa
 
Parancoe and Lambico
Parancoe and LambicoParancoe and Lambico
Parancoe and Lambicobenfante
 
Jpa 2.0 in java ee 6 part ii
Jpa 2.0 in java ee 6  part iiJpa 2.0 in java ee 6  part ii
Jpa 2.0 in java ee 6 part iiLars Lemos
 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?gedoplan
 
Roma introduction and concepts
Roma introduction and conceptsRoma introduction and concepts
Roma introduction and conceptsLuca Garulli
 
Vaadin 7 - Java Enterprise Edition integration
Vaadin 7 - Java Enterprise Edition integrationVaadin 7 - Java Enterprise Edition integration
Vaadin 7 - Java Enterprise Edition integrationPeter Lehto
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Patrycja Wegrzynowicz
 
Jpa Online Final
Jpa Online FinalJpa Online Final
Jpa Online Finalreynolds
 
Lecture: Vaadin Overview
Lecture: Vaadin OverviewLecture: Vaadin Overview
Lecture: Vaadin OverviewJoonas Lehtinen
 
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...Leonardo De Moura Rocha Lima
 
Slice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistenceSlice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistencePinaki Poddar
 
Java persistence api
Java persistence api Java persistence api
Java persistence api Luis Goldster
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Fahad Golra
 
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]Otávio Santana
 

Similar to Spring jpa share (20)

Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Scala vs java 8
Scala vs java 8Scala vs java 8
Scala vs java 8
 
appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
 
Parancoe and Lambico
Parancoe and LambicoParancoe and Lambico
Parancoe and Lambico
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Jpa 2.0 in java ee 6 part ii
Jpa 2.0 in java ee 6  part iiJpa 2.0 in java ee 6  part ii
Jpa 2.0 in java ee 6 part ii
 
En webinar jpa v2final
En webinar jpa v2finalEn webinar jpa v2final
En webinar jpa v2final
 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?
 
Roma introduction and concepts
Roma introduction and conceptsRoma introduction and concepts
Roma introduction and concepts
 
Vaadin 7 - Java Enterprise Edition integration
Vaadin 7 - Java Enterprise Edition integrationVaadin 7 - Java Enterprise Edition integration
Vaadin 7 - Java Enterprise Edition integration
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Jpa Online Final
Jpa Online FinalJpa Online Final
Jpa Online Final
 
Lecture: Vaadin Overview
Lecture: Vaadin OverviewLecture: Vaadin Overview
Lecture: Vaadin Overview
 
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...
JavaOne 2017 - JNoSQL: The Definitive Solution for Java and NoSQL Database [C...
 
Slice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed PersistenceSlice: OpenJPA for Distributed Persistence
Slice: OpenJPA for Distributed Persistence
 
Spring ME
Spring MESpring ME
Spring ME
 
Java persistence api
Java persistence api Java persistence api
Java persistence api
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]
Jakarta EE Meets NoSQL in the Cloud Age [DEV6109]
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Spring jpa share