Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the notes commonly used by SpringDataJPA in Entity?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the notes commonly used by SpringDataJPA in Entity, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

First of all, our commonly used notes include

@ Entity, @ Table, @ Id, @ IdClass, @ GeneratedValue, @ Basic, @ Transient, @ Column, @ Temporal, @ Enumerated, @ Lob

Objects defined by @ Entity using this annotation will become entities managed by JPA and will be mapped to the specified database table @ Entity (name = "user"), where name is the name of this entity class by default and is globally unique.

@ Table specifies the table name of the database corresponding to this entity class. If the annotation does not add a name, the system thinks that the table name and the entity class name are the same.

The @ Id definition field is the primary key of the database, and there must be one in an entity.

@ IdClass uses the federated primary key of the external class, in which the external class must meet the following requirements

The Serializable interface must be implemented.

There must be a default public no-parameter constructor.

The equals and hashCode methods must be overridden. The equals method is used to determine whether two objects are the same, and EntityManger uses the find method to find Entity based on the return value of equals. The hashCode method returns the hash code of the current object, and the smaller the probability of generating the same hashCode, the better. The algorithm can be optimized.

@ GeneratedValue Primary key Generation Policy

The default is AUTO, that is, JPA automatically selects the appropriate policy.

IDENTITY is suitable for MySQL, and the policy is self-increasing.

SEQUENCE generates primary key through sequence specifies sequence name through @ SquenceGenerator MySQL does not support

The primary key is generated by table simulation in TABLE framework, and this strategy is beneficial to database migration.

@ Basic indicates that this field is mapped to the database, and if there are no comments on the entity field, the default is @ Basic. The optional parameter is @ Basic (fetch = FetchType.LAZY, optional = false), where fetch defaults to EAGER loading immediately, LAZY indicates delayed loading, and optional indicates whether the field can be null.

@ Transient and @ Basic do the opposite, indicating that the field is not a field mapping to a database table, and JPA ignores this field when mapping the database.

@ Column defines the column names in the database corresponding to the fields within the entity

@ Column (name = "real_name", unique = true, nullable = false, insertable = false, updatable = false, columnDefinition = "varchar", length = 100)

Name corresponds to the field name of the database. Optional default field names are the same as entity attribute names.

Whether unique is unique. Default false. Optional.

Whether nullable is allowed to be empty. Optional. Default is true.

Whether this field is included when insertable executes insert. Optional, default true

Whether this field is included when updatable executes update. Optional, default true

ColumnDefinition indicates the actual type of the field in the database

Length of length database field. Optional. Default is 25.

@ Temporal is used to set the attribute of the Date type to map to the corresponding precision field.

@ Temporal (TemporalType.DATE) / / mapped to only date @ Temporal (TemporalType.TIME) / / mapped to only time @ Temporal (TemporalType.TIMESTAMP) / / mapped to date + time

@ Lob maps fields to large object types supported by the database, supporting fields of the following two database types. (note: Clob and Blob take up a large amount of memory space, which is generally set to delayed loading with @ Basic (fetch= FetchType.LAZY).)

Clob: field types of Character [], char [], String will be mapped to Clob

Blob: field types Byte [], byte [] and types that implement the Serializable interface will be mapped to Blob types

Next, we will introduce the annotations of association relations.

@ JoinColumn, @ OneToOne, @ OneToMany, @ ManyToOne, @ ManyToMany, @ JoinTable, @ OrderBy

1.@JoinColumn defines the name of the field associated with the foreign key, and the meaning of the attribute is as follows

Name indicates the field name of the target table, required

ReferencedColumnName the field name of this physical table, which is not required. The default is ID of this table.

Whether the unique foreign key field is unique, optional, default false

Whether the nullable foreign key field is allowed to be empty, optional, default true

Whether to add insertable along with the new operation. Optional. Default is true.

Whether the updatable is updated together when it is updated. Optional, default true

@ JoinColumn is mainly used with @ OneToOne, @ ManyToOne, and @ OneToMany. It doesn't make any sense to use it alone.

@ JoinColumns defines the association of multiple fields

2.@OneToOne one-to-one relationship

@ OneToOne (targetEntity = SysRole.class, cascade = {CascadeType.PERSIST,CascadeType.REMOVE,CascadeType.REFRESH,CascadeType.MERGE}, fetch = FetchType.LAZY,optional = false,mappedBy = "userId", orphanRemoval = true)

TargetEntity is not required. Default is the type of this field.

Cascade cascade operation policy CascadeType.PERSIST cascade new, CascadeType.REMOVE cascade delete, CascadeType.REFRESH cascade refresh, CascadeType.MERGE cascade update, CascadeType.ALL all four options

Fetch data loading method. Default EAGER (load now), LAZY (delay load)

Whether optional is allowed to be empty. Optional. Default is true.

Who maintains the mappedBy association relationship is not required and generally does not need to be specified. Note: only the relationship maintainer can operate the relationship between the two, and the maintained party will not update the foreign key association even if the maintainer's properties are set for storage. MappedBy cannot be used with @ JoinColumn or @ JoinTable. The value of mappedBy refers to the field of the attribute in the entity of the other party, not the database field or the name of the entity object, that is, the field name of the attribute of the @ JoinColumn or @ JoinTable annotation configured by the other party.

Whether orphanRemoval is cascaded with deletion, which has the same effect as CascadeType.REMOVE. If you configure one of the two, the deletion will be automatically cascaded.

@ OneToOne needs to be used with @ JoinColumn. It can be associated in both directions, or only one side can be configured. Let's give an example: suppose a user has only one role SysUser as follows

@ OneToOne@JoinColumn (name = "role_id", referencedColumnName = "user_id") private SysRole role;// if two-way association is required, the content of SysRole is as follows: @ OneToOne (mappedBy = "role") private SysUser user;//, of course, you do not have to select mappedBy, and the same is true for @ OneToOne@JoinColumn (name = "user_id", referencedColumnName = "role_id") private SysUser user using the following effect

The relationship between 3.@OneToMany and @ ManyToOne: one-to-many and many-to-one

@ Entity@Table (name= "user") class User implements Serializable {private Long userId; @ OneToMany (cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "user") private Set setRole;} @ Entity@Table (name= "role") class Role {private Long roleId; @ ManyToOne (cascade = CascadeType.ALL,fetch = FetchType.EAGER) @ JoinColumn (name= "user_id") / / user_id field as the foreign key private User user;}

Sort when 4.@OrderBy associates a query, which is usually used with @ OneToMany

@ Entity@Table (name= "user") class User implements Serializable {private Long userId; @ OneToMany (cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "user") @ OrderBy ("role_name DESC") private Set setRole;}

5.@JoinTable association tables are generally used with @ ManyToMany

@ ManyToMany means many to many, and there is also an one-to-many distinction, which has nothing to do with annotations. It only depends on whether entity classes refer to each other.

JoinTable (name = "sys_user_role", joinColumns = {@ JoinColumn (name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@ JoinColumn (name = "role_id", referencedColumnName = "id")}) @ ManyToMany (cascade = {CascadeType.REFRESH}, fetch = FetchType.EAGER) private List roles

@ JoinTable name represents the name of the intermediate association table

The joinColumns in @ JoinTable represents the field of the main link table, that is, the corresponding connection field within the current object

@ JoinTable in roomseJoinColumns represents the foreign key field of the joined table

6.Left Join, Inner join and @ EntityGraph

When using @ ManyToMany, @ ManytoOne, @ OneToMany, @ OneToOne relationships, SQL always executes a query consisting of a main query statement and N sub-query statements. If there are N sub-objects, @ EntityGraph and @ NamedEntityGraph introduced by SQL,JPA2.1 will be executed to improve query efficiency. @ NamedEntityGraph is configured on @ Entity, while @ EntityGraph is configured on the query method of Repository.

NamedEntityGraph (name= "User.addressEntityList", attributeNodes = {@ NamedAttributeNode ("setRole"), @ NamedAttributeNode ("dept")}) @ Entity@Table (name= "user") public class User implements Serializable {private Long userId; @ OneToMany (cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "user") @ OrderBy ("role_name DESC") private Set setRole; @ OneToOne @ JoinColumn (name= "dept_id", referencedColumnName = "user_id") private Department dept;}

Then you only need to annotate the Repository query method with @ EntityGraph, where value is the Name in @ NamedEntityGraph and is configured as follows

EntityGraph (value = "User.addressEntityList") List findAll ()

Note the following for relational queries:

All annotations are either configured on the field or on the get method. If they cannot be mixed, the mixed project will not start.

All associations support one-way and two-way associations. Using two-way annotations when JSON serialization creates an endless loop that requires manual conversion, or use @ JsonIgnore

All associated tables generally do not need to be indexed by foreign keys

Thank you for reading this article carefully. I hope the article "what are the comments commonly used in SpringDataJPA in Entity" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report