Introduction to related annotations of JAVA, Spring, and Spring Boot

0 Preface

Annotation plays an important role in Spring Boot development. Annotations provide a formalized way to add information to the code, through which the annotated object can be easily used somewhere in the code. Common uses of annotations include generating documentation, tracking code dependencies and alternative configuration files, performing format checks at compile time (such as @Override before methods), etc.

This article introduces Spring Boot annotations and Java annotations, Spring annotations, etc. that are closely related to Spring Boot annotations.

1. JAVA annotations

The JRE library package java.lang.annotation code includes annotation-related interfaces, classes, and so on. The interface java.lang.annotation.Annotation is an interface that all custom annotations inherit automatically, and does not need to be specified when defining, similar to the Object class that all JAVA classes inherit automatically.

1.1 Introduction to JAVA annotations

Annotation is a series of metadata, which uses metadata to explain and explain the program code (that is, the annotated object). However, annotations are not part of the annotated code. Annotations have no direct effect on how the code works. The functions of annotations include:

  1. Provide information to the compiler, which can use annotations to detect errors and warnings;
  2. Software tools can use annotation information to generate code, HTML documents or do other corresponding processing;
  3. Runtime processing, some annotations can accept code extraction when the program is running.

Before understanding the specific syntax of annotations, you can think of annotations as a label. Like interfaces and classes, annotations are a type. Annotation is a concept introduced since JAVA 1.5, which allows developers to define their own annotation types and use custom annotations. Annotations are defined with the keyword @interface.

public @interface TestAnnotation {
    
    
    
}

The code in the above example defines an annotation named TestAnnotation, which automatically inherits the class java.lang.annotation.Annotation. Once a custom annotation has been created, the custom annotation can be used. Annotations are used as follows:

@TestAnnotation
public class Test {
    
    
    
}

The above example creates a class Test and adds the @TestAnnotation annotation above the class definition, which means that the class Test is annotated with TestAnnotation.

1.2 Meta-annotations for JAVA

To use annotations better, you also need to understand meta-annotations. Meta-annotations are annotations added to annotations whose purpose is to explain, illustrate, other common annotations. There are five types of meta-annotations: @Retention, @Documented, @Target, @Inherited, and @Repeatable.

  • @Retention When applied to an annotation, it indicates the lifetime of the annotation. Its values ​​include:

    • RetentionPolicy.SOURCE indicates that annotations are only retained at the source code stage and are lost when the compiler compiles;
    • RetentionPolicy.CLASS indicates that annotations are retained until compilation and will not be loaded into the JVM;
    • RetentionPolicy.RUNTIME indicates that annotations can be retained until the program is running, it will be loaded into the JVM, and they can be obtained when the program is running.
    @Retention(RetentionPolicy.RUNTIME)
    public @interface TestAnnotation {
          
          
        
    }
    

    The above means that the annotation TestAnnotation can be obtained when the program is running.

  • @Documented indicates that the content of the annotation will be extracted into a document by the Javadoc tool, and the content of the document will vary depending on the content of the annotation.

  • @Target indicates where the annotation is used, such as types, methods, and fields. The values ​​of the meta-annotation @Target include:

    • ElementType.FIELD represents annotations on fields and enumeration constants;
    • ElementType.METHOD represents the annotation on the method;
    • ElementType.PARAMETER represents annotations on method parameters;
    • ElementType.CONSTRUCTOR represents the annotation to the constructor;
    • ElementType.LOCAL_VARIABLE represents annotations on local variables;
    • ElementType.ANNOTATION_TYPE represents the annotation of the annotation type;
    • ElementType.PACKAGE represents the annotation on the package;
    • ElementType.TYPE represents annotations of any type such as interfaces, classes, enumerations, and annotations.
  • The @Inherited table is automatically inherited, that is, after the annotations annotated by @Inherited are applied to the parent class, the subclass will automatically inherit the annotations of the parent class. The sample code is as follows:

    // 定义注解
    @Inherited
    @Retention(RetentionPoilcy.RUNTIME)
    @interface Test {
          
           }
    
    // 在父类中添加注解
    @Test
    public class A {
          
           }
    
    // 子类 B 虽然没有明确给出注解信息,但是它会继承父类 A 中的注解 @Test
    public calss B extends A {
          
           }
    
  • @Repeatable is an annotation introduced in JAVA 1.8, and the sample code of its application is shown below. Persons can be regarded as a general label, which is filled with labels of the same type but different content. Therefore, SuperMan can be labeled as painter, programmer, product manager, etc. at the same time (that is, add three annotations).

    // Persons 使用数组存放注解的容器注解,它里面必须要有一个 value 属性,即数组
    @interface PerSons {
          
          
        Person[] value();
    }
    
    // 可以重复、多次应用 Persons 注解
    @Repeatable (Persons.class)
    @interface Person {
          
          
        String role default "";
    }
    
    // 不同属性的Person注解
    @Person(role="artist")
    @Person(role="coder")
    @Person(role="PM")
    public class SuperMan {
          
          
        
    }
    

1.3 Properties of Annotations

Annotations can have attributes (also called member variables), and the sample code is as follows. The custom annotation TestAnnotation has two properties of id and msg, and the return types are int and String respectively.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    
    
    int id();
    String msg();
}

When using annotations, attributes should be assigned values. The attribute assignment method is carried out in the form of "attribute = value" after the annotation without brackets, and the assignment of multiple attributes is separated by commas, as shown in the following example. It should be noted that the types of attributes in annotations can only be 8 basic data types, classes, interfaces, annotations and their arrays.

@TestAnnotation(id=3, msg="hello world")
public class Test {
    
     

}

The attribute in the annotation can have a default value, and the default value needs to be specified with the keyword default. The sample code is as follows. The default value of the attribute id in the annotation TestAnnotation is specified as -1, and the default value of the attribute msg is specified as "Hi".

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    
    
    public int id() default -1;
    public String msg() default "Hi";
}

By adding the specified default value of the attribute, it is no longer necessary to assign the attribute in the brackets after the annotation TestAnnotation.

If the annotation has only one attribute, when applying this annotation, the attribute name can be omitted and the attribute value can be directly filled in the brackets after the annotation.

If the annotation does not have any attributes, the parentheses following the annotation can be omitted when applying this annotation.

1.4 Basic annotations of JAVA presets

Under the java.lang package, Java provides five annotations in advance: @Deprecated, @SuppressWarnings, @Override, @SafeVarargs, and @FunctionalInterface.

  • @Deprecated is used to mark deprecated elements. When the compiler encounters this annotation during the compilation phase, it will issue a warning to tell the developer that an outdated element (such as an outdated method, class, or member variable) is being called.
  • @SupperssWarings means to prevent warnings. After using the @Deprecated annotation, the compiler sometimes issues a warning reminder to the developer; when the developer wants to ignore the warning reminder, the @SupperssWarings annotation can be used to achieve the goal. Parameters for @SupperssWarings include:
    • deprecation: means to ignore warnings when outdated elements are used;
    • unchecked: indicates that the warning when an unchecked conversion is performed is ignored;
    • fallthrough: means to ignore the warning when the switch program block directly leads to the next case without break;
    • path: Indicates ignoring warnings when there are paths that do not exist in paths such as classpaths and source file paths;
    • serial: Indicates ignoring warnings when serializable classes lack serialVersionUID definitions;
    • finally: means to ignore any warnings when the finally clause cannot be completed normally;
    • all: Indicates to ignore warnings about all cases.
  • @Override means that the subclass should override the corresponding method of the parent class (or interface). If you want to override the method of the parent class, such as the toString() method, add @Override in front of the method, and the system can help check the correctness of the method. The sample code is as follows:
    // @Override 可以帮忙检查方法的正确性
    @Override
    public String toString() {
          
          ...} // 这是子类方法正确的写法
    
    // 下面子类方法是错误的,有 @Override,系统可以帮忙检查出 tostring 的拼写错误
    @Override
    public String tostring() {
          
          ...}
    
    // 下面子类方法是错误的,由于没有 @Override,系统不会帮助检查出 tostring 的拼写错误
    public String tostring() {
          
          ...}
    
  • @SafeVarargs is used to identify parameter-safe types. It is used to remind developers not to use parameters to do unsafe operations. Its existence will prevent the compiler from generating unchecked warnings. He is an annotation introduced in Java 1.7.
  • @FunctionalInterface is used to specify that an interface must be a functional interface, otherwise a compilation error will occur. @FunctionalInterface is a new feature introduced in Java 1.8. If an interface has one and only one abstract method (which can contain multiple default methods or multiple static methods), the interface is called a functional interface.

2 Spring annotations and annotation injection

The Spring container manages JAVA classes by registering them as Beans. There are two ways to turn JAVA class into Bean: one way is to register JAVA class as Bean through XML configuration; the other way is to register JAVA class as Bean through annotation method. Different annotations can be used to register JAVA classes as different Beans. Compared with XML configuration, the annotation method is more convenient and convenient. As a result, more and more tools support configuration with annotations and abandon XML configuration.

2.1 Spring basic annotations

The annotation @Component can be placed in front of the class, which is marked as a normal bean of Spring.

The annotation @Controller marks a controller component class, which is used to automatically detect components in the classpath and automatically register components as beans. For example, after using the @Controller annotation to mark the Java class UserAction, it means that the class UserAction should be marked as a Bean and handed over to the Spring container for management. If you do not specify a Bean name, the Bean will be named userAction by convention. You can also specify the name of the Bean in the brackets after the annotation, for example, use @Controller(value="UA") or @Controller("UA") to specify the name of the Bean as UA.

The annotation @Service marks a business logic component class. For example, when class Action needs to use UserServiceImpl instance, you can use @Service("uaerService") annotation to tell Spring to create a UserServiceImpl instance (named userService). After Spring creates userService, it can be injected into Action, and Action can use the UserServiceImpl instance.

The annotation @Repository annotates a DAO component class. You can tell Spring to create a UserDao instance (named userDao) with the @Repository(value="userDao") annotation. When the Service needs to use userDao, you can use the @Repository(name="userDao") annotation to tell Spring to inject the created userDao into the Service.

2.2 Spring Common Annotations

The annotation @Autowired is used to implement automatic assembly, and @Autowired can be used to mark objects such as member variables, methods, and constructors. Although the annotation objects of @Autowired are different, they will be automatically assembled when Spring initializes the Bean. Using @Autowired allows the Spring container to automatically search for the required Bean and inject it as a parameter.

@Autowired is autowired according to the type, and the sample code is as follows. If there are multiple beans of the same type in the Spring context (for example, two classes both implement the EmployeeService interface), Spring does not know which implementation class should be bound, and a BeanCreationException will be thrown. If a certain type of bean does not exist in the Spring context, a BeanCreationException will also be thrown.

Example application code annotated with @Autowired:

// 接口 Employeeservice 声明
public interface EmployeeService {
    
    
    public EmployeeDto getEmployeeById(Long ld);
}

// 两个实现类 EmployeeServiceImpl 和 EmployeeServiceImpl1
@Service("service")
public class EmployeeserviceImpl implements EmployeeService {
    
    
    public EmployeeDto getEmployeeById(Long id) {
    
    
        return new EmployeeDto();
    }
}

Service("service1")
public class EmployeeServiceImpll implements EmployeeService {
    
    
    public EmployeeDto getEmployeeById(Long id) {
    
    
        return new EmpioyeeDto();
    }
}

// 调用接口实现类
@Controller
@RequestMapping("/emplayee.do")
public class EmployeeInfoControl {
    
    
	@Autowired//此注解处会出错,因为有两个实现类,而不知道绑定哪一个
	EmployeeService employee5ervice;
	
    @RequestMapping(params = "method=showEmplayeeInfo")
    public void showEmplayeeInfo(HttpServletRequest request, HttpservletRespcnmresponse, EmployeeDto dto) {
    
    
        ... // 代码省略
    }
}

You can use @Qualifier with @Autowired to solve the abnormal BeanCreationlException, the sample code is as follows:

// 接口 Employeeservice 声明与上例一致
// 接口的两个实现类 EmployeeserviceImpl 和 EmployeeserviceImpl1 与上例一致

// 接口实现类的调用
@Controller
@RequestMapping("/emplayee.do")
public class EmployeeInfoControl {
    
    
    @Autowired
    @Qualifier( "service") // 新增加语句,指定调用第一个接口实现类
    EmployeeService employeeService;
    @RequestMapping(params = "method=showEmplayeeInfo")
    public void showEmplayeeInfo(HttpServletRequest request, HttpservletRespcnmresponse, EmployeeDto dto) {
    
    
        ... // 代码省略
    }
}

The annotation @Resource can be used to annotate the SET method of an object. The annotation @Resource is equivalent to @Autowired, except that @Autowired is automatically injected by type, while @Resource is automatically injected by name by default. The JSR-250 standard recommends using the generic annotation @Resource instead of Spring's proprietary @Autowired annotation.

JSR (Java Specification Requests, Java Specification Proposal) is a formal request to JCP (Java Community Process) to add a new standardized technical specification. Anyone can submit a JSR to add new APIs and services to the Java platform. JSR has become an important standard in the Java world. Starting with Spring 2.5, the core of the Spring framework supports the annotations @Resource, @PostConstruct and @PreDestroy in the JSR-250 standard.

@Resource has two important attributes, namely the name name and the attribute type. Spring resolves the @Resource annotation name attribute to the Bean's name, and resolves the type attribute to the Bean's type. If the name attribute is used, the injection strategy of automatic injection by name is used, and when the type attribute is used, the injection strategy of automatic injection by type is used. If neither the name attribute nor the type attribute is specified, the injection strategy of automatic injection by name will be used through the reflection mechanism. When @Resource uses the injection strategy of automatic injection by name, it has the same effect as using @Qualifier to explicitly specify the name of the Bean for injection. Among many identical beans, the @Primary annotated beans are preferred. This is a bit different from @Qualificr, @Qualificr refers to which Bean is used for injection.

Both the annotation @PostConstruct and the annotation @PreDestroy are JSR-250 standard annotations. Methods marked with @PreDestroy will be called before the class is destroyed, and methods annotated with @PostConstruct will be called after the class is instantiated.

Starting from Spring 3.0, Spring began to support JSR-330 standard annotations. In JSR-330, @Inject has the same responsibilities as @Autowired in Spring, and @Named has similar responsibilities as @Component in Spring.

You can use the annotation @Scope to define the scope of the Bean (called scope), or you can achieve this by setting the value of the scope attribute of the Bean in the XML file. The value of the @Scope annotation can be scopes such as singleton, prototype, request, session, and global scsssion. The default is the singleton mode, that is, scope="singleton". in:

  • The singleton mode singleton means that there is only one instance globally;
  • The prototype mode prototype means that there will be a new instance every time the Bean is obtained;
  • request indicates that a new Bean will be generated for each HTTP request, and the Bean is only valid within the current HTTP request;
  • session indicates that a new bean will be generated for each HTTP request, and the bean is only valid within the current HTTP session;
  • A global session is similar to a standard HTTP session, but it only makes sense in portlet-based Web applications.

Portlet request processing is divided into action phase and render phase. In a request, the action phase is executed only once, but the render phase may be executed multiple times due to the user's browser actions. The Portlet specification defines the concept of a global session, which is shared by all the various portlets that make up a Portlet Web application. Beans defined in the global session are scoped to the lifetime of the portlet's global session (global scsssion). If you use global session to identify Bean in Web, then Web will be used as session type automatically.

The default scope of JSR-330 is similar to Spring's prototype, and the Bean in the ISR-330 standard is also a singleton by default in Spring. To use non-singleton scopes, developers should use Spring's @Scope annotation. JSR-330 also provides a @Scope annotation, however, this annotation can only be used when creating a custom scope.

The annotation @RequestMapping specifies a mapping path for a class or method, and the corresponding class or method can be accessed through the specified path. The application example is shown in the following example. Among them, the userid value is bound through the @PathVariable annotation method. The annotation @PathVariable is mainly used to obtain a single URI parameter. If you want to transmit some complex parameters through the URI, you should consider using the annotation @MatrixVariable. The matrix variables of @MatrixVariable can appear anywhere in the URI, and the variables are separated by semicolons (;). @MatrixVariable is not enabled by default. To enable it, enable-matrix-variablcs needs to be set to true.

Sample application code annotated with @RequestMapping.

@RequestMapping(value="/getName/{userid}", method = RequestMethod.Get)
public void login(@Pathvariable String userid, Model mcdel){
    
    
    
}

The annotation @RequestParam assigns the value in the request to the annotated method parameter. As shown in the following example, assign the value username in the request to the username parameter in the method. The attribute required represents whether the parameter must be assigned a value, and the default is true; when it is not sure whether there is a value in the request that can be assigned to the parameter, the attribute required must be set to false.

public void login(@RequestParam(value="username" required="true") String username){
    
    
}

Whether it is an HTTP request or an HTTP response, it is transmitted through a message, and the message has a header and a body. The header contains some information about the server or client, which is used to indicate identity, provide authentication or restrictions, and so on. The body is the content to be passed. The annotation @RequestBody automatically converts the body in the request message into a variable string bound to the method parameter. When responding to a request, @ResponseBody converts the content or Java object into the body of the response message and returns it. The @RequestBody annotation is only used when the returned data is not an HTML markup page (view) but some other format data (such as JSON, XML, etc.).

The annotation @Param represents the interpretation of the parameter, which is generally written in the annotation.

The annotation @JoinTable indicates the mapping relationship between Java classes and database tables, and can also identify column mapping, primary key mapping, etc.

The annotation @Transational is an annotation for Spring transaction management. The method or class annotated by @Transational is automatically registered as a transaction and accepts the management of the Spring container.

The annotation @Syschronized means to implement the Java synchronization mechanism, and using it as an annotation is equivalent to adding a synchronization lock.

The annotation @ModelAttribute is declared on the attribute, indicating that the value of the attribute comes from the queryBean in the model and is saved in the model. The annotation @ModelAttribute is declared on the method, indicating that the return value of the method is saved in the model.

The annotation @Cacheable indicates that the return value of a method should be cached, and the annotation @CacheFlush declares that a method is a trigger to clear the cache. These two annotations should be used in conjunction with the cache processor.

Spring allows you to specify which attributes in the ModelMap need to be dumped into the session so that the next request can still access these attributes. The annotation @SessionAttributes can only annotate classes, not methods.

If you want a property editor to only work on a specific controller, you can define a method annotated @InitBinder in the Controller, and you can register several property editors with the Controller in this method.

The annotation @Required is responsible for checking whether the SET method of a Bean is executed during initialization. If the SET method is not called, Spring will throw an exception during parsing to remind the developer to set the corresponding property. The @Required annotation can only be marked on the SET method, and it will be ignored if it is marked on the non-SET method.

The conditional configuration feature was introduced in Spring 4.0, which provides a more general condition-based Bean creation method: using the @Conditional annotation. @Conditional creates a specific bean based on the satisfaction of a certain condition. Conditional configuration allows configuration to exist in the application, but to ignore it until certain conditions are met. You can easily write custom conditions in Spring, just implement the Condition interface and override its matches() method; as shown in the following example. In the following example, the MyService bean will only be created when the condition of the JdbcTemplateCondition class is true. Otherwise, the Bean declaration will be ignored.

//具体条件类,需实现 Condition 接口,并重写 matches(...,...) 方法
public class JdbcTemplateCondition implements Condition {
    
    
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
    
    
        try{
    
           
            context.getc1assLoader().1oadclass(
        "org.springframework.jdbc.core.JdbcTemplate");
            return true;
        } catch (Exception e) {
    
    
            return false;
        }
    }
                                    
    //声明bean时,使用自定义条件类,作为eConditional的参数value
	@Conditional(JdbcTemplateCondition.class)
	public MyService myService(){
    
    ...}
}

2.3 Spring annotation injection

Annotation injection is achieved through annotations. Common annotations related to injection in Spring include @Autowired, @Resource, @Qualifier, @Service, @Controller, @Repository, @Component, etc. in:

Annotate @Autowired to achieve automatic injection;

The annotation @Resource is injected by specifying the name;

The annotation @Qualifier is used in conjunction with the annotation @Autowired to inject by specifying the name;

Annotation @Autowired, @Resource can be used to annotate fields, constructors, methods, and inject them.

The annotations @Service, @Controller, and @Repository are used to annotate the class, and the Bean to be generated when Spring scans the annotated class. The classes annotated with @Service, @Controller, and @Repository are respectively located in the service layer, control layer, and data storage layer. Annotation @Component is a general term that marks the annotated object as a component.

The annotation @EnableAspectJAutoProxy means to enable the automatic configuration mechanism of the AOP proxy. You can use the AOP framework to expose the proxy object by setting @EnableAspectJAutoProxy(exposeProxy=true), so that aopContext can access it. It can be seen from the definition of the annotation @EnableAspectJAutoProxy that it introduces an AspectJAutoProxyRegister.class object, which is an AnnotationAwareAspectJAutoProxyCreator marked with the @EnableAspectJAutoProxy annotation.

AnnotationAwareAspectJAutoProxyCreator can register an AOP proxy object generator by calling the method registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry) of class AopConfigUtils.

The annotation @Profiles provides a way to isolate application configurations so that these configurations can only take effect in specific environments. Any component or configuration class can be marked with @Profiles to limit when they are loaded.

3 Annotations for Spring Boot

3.1 Spring Boot basic annotations

The annotation @SpringBootApplication is equivalent to the annotation @Configuration, @EnableAutoConfiguration, @ComponentScan annotation. Among them, the annotation @Configuration is marked on the class, which is equivalent to the Bean in Spring's XML configuration file. The annotation @EnablcAutoConfiguration implements automatic configuration. Annotation @ComponentSca scans components, automatically discovers and assembles Beans, and adds Beans to the program context.

The annotation @RestController is a collection of annotations @Controller and @ResponscBody, indicating that the marked object is a REST-style bean, and the return value of the method is directly filled in the HTTP response body and returned to the user.

The annotation @JsonBackReference can be used to solve the problem of infinite recursive calls. The annotation @RepositoryRestResource is used with spring-boot-starter-data-rest to create a RESTful entry point. The annotation @Import is used to import other configuration classes. Annotation @ImportResource is used to load XML configuration files.

The @Bean annotation method is equivalent to the Bean in the XML configuration. The annotation @Value injects the property value configured in the Spring Boot configuration file application.properties. The annotation @Inject is equivalent to the default @Autowired, but without the required attribute.

Spring Boot defines many conditions and applies them to configuration classes, which constitute Spring Boot's automatic configuration. The conditional annotations provided by Spring Boot include @ConditionalOnBean (a specific Bean is configured), @ConditionalOnMissingBean (no specific Bean is configured), @ConditionalOnClass (the specified class is in the classPath directory), @ConditionalOnMissingClass (the specified class is missing in the classpath directory) class), @ConditionalOnExpression (the given SpEL expression evaluates to true), @ConditionalOnJava (the version of Java matches a specific value or a range of values), @ConditionalOnJndi (one must exist for the given JNDI location in the parameter), @ConditionalOnProperty (the specified configuration property has an explicit value), @ConditionalOnResource (the classpath directory has the specified resource), @ConditionalOnWebApplication (is a web application), @ConditionalOnNotWcbApplication (is not a web application).

3.2 JPA annotations

The annotation @Entity indicates that the marked object is an entity class, and the annotation @Table(name=" ") indicates the table name corresponding to the entity; these two annotations are generally used together. But if the table name is the same as the entity class name, @Table can be omitted.

When working on a development project, the operation of mapping entity classes to database tables is often used. Sometimes several entity classes that need to be mapped have common attributes, such as number ID, creator, creation time, remarks, etc. At this time, these attributes can be abstracted into a parent class, and then each entity class inherits this parent class. You can use the @MappedSuperclass annotation to annotate the parent class, which will not be mapped to the database table, but the subclass will automatically scan the mapping properties of the parent class when mapping, and add these properties to the database table corresponding to the subclass. After using the @MappedSuperclass annotation, there cannot be any @Entity or @Table annotations.

SpringData provides many DAO interfaces, but it still may not meet the needs of daily applications, and requires a custom Repository implementation. The annotation @NoRepositoryBean is generally used as the Repository of the parent class. With this annotation, Spring will not instantiate the Repository.

The annotation @Column identifies the correspondence between the attributes in the entity class and the fields in the data table. If the field name of the annotation @Column is the same as the column name, it can be omitted. The @Column annotation has a total of 10 attributes, all of which are optional. Common attributes include name, unique, nullable, table, length, precision, scale, etc. Among them, the name attribute defines the name of the field corresponding to the labeled field in the database table. The unique attribute indicates whether the field is a unique identifier, and the default value is false. If you have a field in the table that needs to be uniquely identified, you can either use this tag or @UniqueConstraint in the @Table tag. The nullable attribute indicates whether the field can be a null value, and the default value is true. The table attribute defines the name of the table containing the current field. The length attribute indicates the length of the field. This attribute is only valid when the type of the field is varchar; the default value is 255 characters. The precision attribute and the scale attribute represent precision. When the field type is double, precision represents the total length of the value, and scale represents the number of digits occupied by the decimal point.

The annotation @Id is used to declare that the attribute of an entity class is mapped to the primary key column of the database. The attribute is usually placed before the attribute declaration statement, and it can go with the declaration statement or be written on a separate line. The @Id annotation can also be placed before a property's getter method.

The annotation @GeneratedValue is used to mark the generation strategy of the primary key, and the strategy is specified through the attribute strategy. For example, the annotation @GeneratedValue(strategy=GenerationType.SEQUENCE) indicates that the primary key generation strategy is scquence, and @GeneratedValue(generator="repair_scq") specifies that the sequence name is repair_seq.

Several alternative strategies such as IDENTITY, AUTO, and SEQUENCE are defined in javax.persistcnce.GenerationTypec. Among them, the IDENTITY strategy means that the database ID self-growth method is used to increase the primary key field. Oracle does not support this method; SEQUENCE means that the primary key is generated through a sequence, and the sequence name is specified through the @SequenceGenerator annotation. MySOL does not support this method. By default, JPA automatically selects the most suitable primary key generation strategy for the underlying database. For example, the default strategy for SQL Server is identity, and the default strategy for MySQL is auto increment. The name in the annotation @SequenceGeneretor(name = "repair_seq", sequenceName = "seq_repair", allocationSize=1) is the name of the sequence, so that sequenceName can be used as the sequence name of the database, and the two names can be consistent.

The annotation @Transient indicates that the marked attribute is not a mapping to a field of a database table, and the Object Relational Mapping (Objcct Relational Mapping, ORM) framework will ignore this attribute. If an attribute is not a field mapping of a database table, it must be marked as @Transicnt; otherwise, the ORM framework defaults to its annotation as @Basic. The annotation @Basic(fetch=FctcbType.LAZY) can specify the loading method of entity attributes.

The function of the annotation @Jsonlgnore is to ignore some properties in the Java Bean during JSON serialization, and both serialization and deserialization are affected. For example, if you want the returned JSON data not to contain the snapshot values ​​of the attributes goodsInfo and extendsInfo; just add @JsonIgnore to the snapshot attribute of the entity class, and the returned JSON data will not contain the two attribute values ​​of goodsInfo and extendsInfo.

The annotation @JoinColumn(name="loginld") indicates that a table has a foreign key pointing to another table. Assuming that the Person table and the Address table are in a one-to-one relationship, Person has a field addressID pointing to the primary key of the Address table; you can use the annotation @JoinColumn to annotate addressID. @OncToOne, @OneToMany, @ManyToOne, @ManyToMany correspond to one-to-one, to-many, many-to-one, many-to-many relationships in the Hibernate configuration file. @ManyToOne does not generate an intermediate table, you can use @Joincolumn(name=" ") to specify the name of the foreign key. @OneToMany will generate an intermediate table, you can use @onetoMany @Joincolumn(name=" ") to avoid generating an intermediate table, and you can specify the name of the foreign key.

3.3 Exception handling annotations

The annotation @ControllerAdvice contains the annotation @Component, which can be scanned and handle exceptions uniformly.

The annotation @ExccptionHandler(Exception.class) is used on the method to indicate that the annotated method will be executed when this exception is encountered.

3.4 Annotation configuration analysis and usage environment

The annotation @PreUpdate is used to specify the callback method for the corresponding lifecycle event. This annotation can be applied to methods of entity classes, mapped superclasses, or callback listener classes. If you want to update the properties every time the entity is updated, you can use the annotation @PreUpdate annotation. The annotation @PreUpdate does not allow changes to entities.

Annotation @PrePersist helps autofill entity properties before persistence. The @PrePersist event occurs immediately after the persist() method is called, and the data at this time has not been actually inserted into the database. It can be used to record some business-independent fields when using JPA, such as the last update time. Lifecycle method annotations (remove no lifecycle events @PrePersist are called before saving, annotations @PostPersist are called after saving. @PostPersist events occur after data has been inserted into the database.

The annotation @PostLoad is called after the Entity is mapped, and the annotation @EntityListeners specifies the implementation class of the external life synchronization event. Annotation @PostLoad event is executed after executing EntityManager.find() or getreference() method to load an entity, after executing JPA SQL query or after EntityManager.refresh() method is called.

Annotation @PreRemove and annotation @PostRemove events are triggered by deleting entities. The annotated @PreRemove event fires before the entity is removed from the database. The annotated @PostRemove event fires after an entity has been removed from the database.

The annotation @NoArgsConstructor provides a parameterless constructor. The annotation @AllArgsConstructor provides a full-parameter constructor.

Guess you like

Origin blog.csdn.net/meng_xin_true/article/details/129935169