当前位置:网站首页>@JPA annotation in entity
@JPA annotation in entity
2022-07-23 19:02:00 【InfoQ】
JPA In the agreement Entity Relevant provisions
- Entities are domain objects that directly perform database persistence operations ( That is, a simple POJO, It can be divided according to business areas ), Must pass @Entity Mark with notes .
- An entity must have a public perhaps protected The nonparametric construction method of .
- The annotation of persistent mapping can be marked in Entity Field of field On , As shown below :
@Column(length = 20, nullable = false)
private String userName;
@Column(length = 20, nullable = false)
public String getUserName(){
return userName;
}
- As long as it's in the @Entity The fields annotated in the entity of , Will be mapped to the database , Besides using @Transient Outside the field of the annotation .
- There must be a primary key in the entity , The field marked by the primary key can be a single field , It can also be a composite primary key field .
What are the detailed notes ?

- @Entity The object used to define will become JPA Managed entities , Required , Map the field to the specified database table , It's simple to use , It can be directly used on entity classes , The syntax expressed through the source code is as follows :
@Target(TYPE) // Indicates that this annotation can only be used in class above
public @interface Entity {
// Optional , The default is the name of the entity class , The whole application is globally unique .
String name() default "";
}
- @Table Used to specify the table name of the database , Represents the table name in the database corresponding to this entity , Not required , Default table name and entity Name the same .
@Target(TYPE) // The same can only be used on classes
public @interface Table {
// Name of table , Optional . If not , The system considers the names of good entities as table names .
String name() default "";
// This table is located in schema, Optional
String schema() default "";
// Uniqueness constraint , Useful when creating tables , After the table is created, it is unnecessary .
UniqueConstraint[] uniqueConstraints() default { };
// Indexes , Use... When creating tables , After the table is created, it is unnecessary .
Index[] indexes() default {};
}
- @Access Is used to specify the entity The annotation inside is written on the field , still get/set The method works above , Not required . If it is not filled in by default , When the first annotation in the entity appears on the field or get/set On the way , Take the first appearance as the standard ; in other words , Annotations in an entity are useful both in field above , Useful in properties When it's up , Look at the code below and you will understand .
@Id
private Long id;
@Column(length = 20, nullable = false)
public String getUserName(){
return userName;
}
@Target( { TYPE, METHOD, FIELD })// Indicates that this annotation can be applied to class On ( At this time, you can specify the default annotation effective policy of this entity ), It can also be used in methods or fields ( Indicates that the effective policy of a field or method can be set independently );
@Retention(RUNTIME)
public @interface Access {
// Specify whether fields or methods are effective
AccessType value();
}
public enum AccessType {
FIELD,
PROPERTY
}
- @Id Define the attribute as the primary key of the database , An entity must have a primary key , But not necessarily this annotation , You can talk to @GeneratedValue Used together or in pairs .
- @GeneratedValue Primary key generation policy , As shown below :
public @interface GeneratedValue {
//Id Generation strategy for
GenerationType strategy() default AUTO;
// adopt Sequences Generate Id, Common is Orcale database ID Generate rules , At this time, we need to cooperate @SequenceGenerator Use
String generator() default "";
}
public enum GenerationType {
// Generate primary key through table , The framework generates the primary key from the table simulation sequence , Using this strategy can make the application easier to migrate .
TABLE,
// Generate primary key through sequence , adopt @SequenceGenerator The annotation specifies the sequence name , MySql Not in favor of this way ;
SEQUENCE,
// Use database ID Self growth , Commonly used in mysql database
IDENTITY,
//JPA Automatically choose the right strategy , Is the default option ;
AUTO
}
- @Enumerated This annotation is easy to use , Because it's good for enum Subscripts and name Two ways , Usage is directly mapped to enum Enumeration type field . Please see the source code below .
@Target({METHOD, FIELD}) // Act on methods and fields
public @interface Enumerated {
// Enumerate the types of mappings , The default is ORDINAL( That is, the subscript of the enumeration field ).
EnumType value() default ORDINAL;
}
public enum EnumType {
// Map the subscript of the enumeration field
ORDINAL,
// Mapping enumerations Name
STRING
}
// There is an enumeration class , Gender of user
public enum Gender {
MAIL(" men "), FMAIL(" women ");
private String value;
private Gender(String value) {
this.value = value;
}
}
// Entity class @Enumerated Let's write it as follows
@Entity
@Table(name = "tb_user")
public class User implements Serializable {
@Enumerated(EnumType.STRING)
@Column(name = "user_gender")
private Gender gender;
.......................
}
- @Basic Indicates that the attribute is a mapping to the field of the database table . If there is no annotation on the field of the entity , Default is @Basic. That is to say, by default, all fields must be mapped to the database , And the default is Eager type .
public @interface Basic {
// Optional ,EAGER( Default ): Immediately load ;LAZY: Delay loading .(LAZY It is mainly applied to large fields )
FetchType fetch() default EAGER;
// Optional . Whether this field can be null, The default is true.
boolean optional() default true;
}
- @Transient Indicates that the property is not a field mapping to a database table , Represents a non persistent property .JPA Ignore it when mapping the database , And @Basic Has the opposite effect . That is, above each field @Transient and @Basic You have to choose between , If nothing is specified , The default is @Basic.
- @Column Define the column name in the database corresponding to this attribute .
public @interface Column {
// Column names of tables in the database ; Optional , If it is not filled in, it is considered that the field name is the same as the entity attribute name .
String name() default "";
// Is it unique? . Default flase, Optional .
boolean unique() default false;
// Whether the data field can be null . Optional , Default true.
boolean nullable() default true;
// perform insert Whether this field is included in the operation , Default ,true, Optional .
boolean insertable() default true;
// perform update Whether this field is included in the , Default ,true, Optional .
boolean updatable() default true;
// Represents the actual type of the field in the database .
String columnDefinition() default "";
// The length of the database field , Optional , Default 255
int length() default 255;
}
- @Temporal Used to set Date The attribute of type is mapped to the field of corresponding precision , There are three situations :
- @Temporal(TemporalType.DATE) Map to date // date (Only the date)
- @Temporal(TemporalType.TIME) Map to date // time (Only time)
- @Temporal(TemporalType.TIMESTAMP) Map to date // date time (date + Time)
package com.example.jpa.example1;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "user_topic")
@Access(AccessType.FIELD)
@Data
public class UserTopic {
@Id
@Column(name = "id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "title", nullable = true, length = 200)
private String title;
@Basic
@Column(name = "create_user_id", nullable = true)
private Integer createUserId;
@Basic(fetch = FetchType.LAZY)
@Column(name = "content", nullable = true, length = -1)
@Lob
private String content;
@Basic(fetch = FetchType.LAZY)
@Column(name = "image", nullable = true)
@Lob
private byte[] image;
@Basic
@Column(name = "create_time", nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date createTime;
@Basic
@Column(name = "create_date", nullable = true)
@Temporal(TemporalType.DATE)
private Date createDate;
@Enumerated(EnumType.STRING)
@Column(name = "topic_type")
private Type type;
@Transient
private String transientSimple;
// Non database mapped fields , Field of business type
public String getTransientSimple() {
return title + "auto:jack" + type;
}
// There is an enumeration class , The type of topic
public enum Type {
EN(" english "), CN(" chinese ");
private final String des;
Type(String des) {
this.des = des;
}
}
}
边栏推荐
- Cell array processing
- Is learning next generation modeling a good scene or a good role? Choose the right profession and pay more than half
- Tcl脚本语言基础(2)
- Terminal终端命令(全)
- [paper reading] gettext: trajectory flow map enhanced transformer for next POI recommendation
- 11. Basic concepts of neural network
- Source code analysis of ThreadPoolExecutor
- 1259. Disjoint handshake dynamic programming
- 【2022】【论文笔记】太赫兹量子阱——
- Detailed explanation: tmp1750 chip three channel linear LED driver
猜你喜欢

Jetpack Compose之Navigation组件使用
![MySQL [knowing and mastering one article is enough]](/img/5a/ed8f1d3fac63d329a28ebf6d4974f5.png)
MySQL [knowing and mastering one article is enough]
![[2020] [paper notes] Based on Rydberg atom——](/img/5c/186cae4e47a236ae4062d15f839196.png)
[2020] [paper notes] Based on Rydberg atom——

1259. Disjoint handshake dynamic programming

LM393低功耗双电压比较器参数、引脚、应用详解

【攻防世界WEB】难度四星12分进阶题:Cat

Building virtual private network based on softther
![[sharing 3D modeling and production skills] how ZBrush turns pictures into relief models](/img/fc/c400821c07ea43576a14a30d96183f.png)
[sharing 3D modeling and production skills] how ZBrush turns pictures into relief models

Paddlenlp之UIE分类模型【以情感倾向分析新闻分类为例】含智能标注方案)

Problems and methods of creating multiple projects under one solution in VS2010
随机推荐
MQ [messagequeue graphic explanation and four MQ comparisons]
What problems do you usually encounter when learning 3D modeling? It's too much
[whole process of game modeling model production] ZBrush weapon model production: Crossbow
The first layer of OSI model: physical layer, the cornerstone of existence!
多线程【全面学习 图文精讲】
1259. 不相交的握手 動態規劃
BOM introduction of BOM series
Building virtual private network based on softther
Emgucv common function function description "suggestions collection"
What is the current situation of the next generation industry? 90% of career changing modelers are learning this process
Problems and methods of creating multiple projects under one solution in VS2010
手写bind、call、apply其实很简单
Error reporting caused by the use of responsebodyadvice interface and its solution
How to realize the digital transformation of the banking industry
使用kail破解wifi密码
MySQL [knowing and mastering one article is enough]
银行业如何实现数字化转型风口全速启航
Handwriting bind, call, apply is actually very simple
【攻防世界WEB】难度三星9分入门题(终):fakebook、favorite_number
基於FPGA的UART接口設計