This article introduces four advanced mapping methods of JPA. 1. Bidirectional association specifies the relationship maintainer through mappedBy to enable user and Address to access each other; 2. Many-to-many association uses @ManyToMany and @JoinTable to manage intermediate tables, or manually create entity classes to expand intermediate table functions; 3. Embed object uses @Embeddable and @Embedded to embed Address into the Order table, supporting compound primary key design; 4. The inheritance structure uses SINGLE_TABLE, JOINED, and TABLE_PER_CLASS policies to map Employee subclasses, and select appropriate solutions according to query needs.
When using the Java Persistence API (JPA), in addition to basic entity mapping, mastering some advanced mapping techniques can help us more flexibly handle complex data models and business logic. This article will introduce several practical advanced JPA mapping methods, including advanced usage of one-to-one, one-to-many, and many-to-many relationships, as well as the processing of nested objects and inherited structures.

1. Two-way relationship: make the relationship more controllable
In actual development, in many cases we need two entities to be able to access each other. For example, user (User) and address (Address), a user can have an address, and an address may also belong to a certain user.
@Entity public class User { @Id private Long id; @OneToOne @JoinColumn(name = "address_id") private Address address; } @Entity public class Address { @Id private Long id; @OneToOne(mappedBy = "address") private User user; }
The key here lies in the use of
mappedBy
, which tells JPA which party to maintain the relationship. It is usually recommended that the "owner" manage foreign keys, and the other party references them throughmappedBy
.
Tips:
- Bidirectional relationships are prone to cause circular reference problems, especially when serializing into JSON.
- Using
@JsonManagedReference
and@JsonBackReference
can avoid the infinite recursion problem of Jackson serialization.
2. Many-to-many association: how to process intermediate tables
When there is a many-to-many relationship between two entities, JPA provides concise annotation support, but an intermediate table will be automatically generated behind it. For example, the relationship between student and course:

@Entity public class Student { @Id private Long id; @ManyToMany @JoinTable( name = "student_course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id") ) private Set<Course> courses = new HashSet<>(); }
@Entity public class Course { @Id private Long id; @ManyToMany(mappedBy = "courses") private Set<Student> students = new HashSet<>(); }
If you want to do extra operations on the intermediate table (such as recording creation time or status), you need to manually create the intermediate entity class to replace the default JoinTable.
Note:
- When inserting data many to many, the referenced party (such as Course) needs to be saved first, otherwise an exception may be thrown.
- Be careful when modifying a collection to avoid inconsistency in data due to incorrect synchronization of the two-side relationship.
3. Embed objects and composite primary keys: data modeling that is closer to reality
Sometimes we encounter some fields of an entity that can be abstracted into another object, but do not need to exist as a table alone. At this time, you can use @Embeddable
and @Embedded
annotations.
For example, an order address information can be used as an embedded object:
@Embeddable public class Address { private String street; private String city; private String zipCode; } @Entity public class Order { @Id private Long id; @Embedded private Address shippingAddress; }
In the database table generated in this way, the Order table will directly contain street
, city
, zipCode
fields.
If multiple fields combine to form a primary key, you can also use @Embeddable
to define a composite primary key class and reference it with @EmbeddedId
in the entity.
4. Inheritance structure mapping: How to persist class inheritance relationships
JPA supports three common inheritance strategies, suitable for different scenarios:
- SINGLE_TABLE : All subclasses share a table, and use a discriminator column to identify the type.
- JOINED : Each subclass has its own table, and the parent class table is connected by foreign keys.
- TABLE_PER_CLASS : Each subclass is a complete table without sharing structure.
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "employee_type") public abstract class Employee { ... } @Entity @DiscriminatorValue("fulltime") public class FullTimeEmployee extends Employee { ... }
A common practice is to select a strategy based on the query frequency. Single tables are suitable for frequent cross-type queries, and JOINED is more in line with the paradigm but has slightly poor query performance.
Basically these common but easily overlooked advanced JPA mapping methods. Mastering them not only improves code flexibility, but also better deal with complex business models. Only by rationally using annotations and strategies can the greatest value of JPA be achieved.
The above is the detailed content of Java Persistence API (JPA) Advanced Mappings. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Lazy loading only queries when accessing associations can easily lead to N 1 problems, which is suitable for scenarios where the associated data is not determined whether it is needed; 2. Emergency loading uses with() to load associated data in advance to avoid N 1 queries, which is suitable for batch processing scenarios; 3. Emergency loading should be used to optimize performance, and N 1 problems can be detected through tools such as LaravelDebugbar, and the $with attribute of the model is carefully used to avoid unnecessary performance overhead.

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

Python's memory management is based on reference counting and garbage collection mechanisms. 1. The reference counting mechanism ensures that objects are released immediately when the reference number is 0. The return value of sys.getrefcount() is 1 more than the actual reference because it increases its reference itself; 2. Circular references cannot be cleaned through reference counting, and it depends on the generational recycling of the gc module. Calling gc.collect() can recycle unreachable objects; 3. In actual development, long-term holding of large object references should be avoided. We can use weakref weak references, timely place None to release memory, and use tracemalloc to monitor memory allocation; 4. Summary: Python combines reference counting and garbage collection to manage memory, developers can use tools and optimize reference pipes.

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

Responsive programming implements high concurrency, low latency non-blocking services in Java through ProjectReactor and SpringWebFlux. 1. ProjectReactor provides two core types: Mono and Flux, supports declarative processing of asynchronous data flows, and converts, filters and other operations through operator chains; 2. SpringWebFlux is built on Reactor, supports two programming models: annotation and functional. It runs on non-blocking servers such as Netty, and can efficiently handle a large number of concurrent connections; 3. Using WebFlux Reactor can improve the concurrency capability and resource utilization in I/O-intensive scenarios, and naturally supports SSE and WebSo.

MapStruct is a compile-time code generator used to simplify mapping between JavaBeans. 1. It automatically generates implementation classes by defining interfaces to avoid manually writing lengthy set/get mapping code; 2. It has type-safe, no runtime overhead, supports automatic mapping of the same name fields, custom expressions, nested objects and collection mapping; 3. It can be integrated with Spring and uses @Mapper(componentModel="spring") to inject mapper into Springbean; 4. Simple configuration, just introduce mapstruct dependencies and annotationProcessorPaths inserts

Use regular expression capture group in Notepad to effectively reorganize text. First, you need to open the replacement dialog box (Ctrl H), select "Search Mode" as "regular expression", 1. Use () to define the capture group, such as (\w ) to capture words; 2. Use \1 and \2 to reference the corresponding group in the replacement box; 3. Example: Exchange the name "JohnDoe" as "Doe, John", find (\w )\s (\w ), replace it with \2,\1; 4. Date format conversion 2023-12-25 to 25/12/2023, find (\d{4})-(\d{2})-(\d{2}), replace it with \3/\2/\1; 5. Log reordering can extract time, level, ID and other information

UseefficientdatastructureslikeArrayListoverLinkedListandprimitivecollectionstoreduceoverhead;2.Minimizeobjectcreationbyreusingobjects,usingStringBuilderforconcatenation,andcachingexpensiveobjects;3.Preventmemoryleaksbynullifyingreferences,usingstatic
