SlideShare une entreprise Scribd logo
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

Contenu connexe

Similaire à Spring jpa share

appengine java night #1
appengine java night #1appengine java night #1
appengine java night #1
Shinichi Ogawa
 
Jpa Online Final
Jpa Online FinalJpa Online Final
Jpa Online Final
reynolds
 

Similaire à 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]
 

Dernier

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Dernier (20)

Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 

Spring jpa share