theme: cyanosis highlight: arta

Official account: Java Xiaokaxiu, website: Javaxks.com

Author: v. v. – sauce, link: blog.csdn.net/weixin_40753536/article/details/81285046

Advantages of using annotations:

  1. Using pure Java code, there is no need to configure complex XML files
  2. You can also enjoy the benefits of object orientation in your configuration
  3. Type safety provides good support for refactoring
  4. You can enjoy the functionality provided by the springIoC container while reducing complex configuration files

A detailed explanation of annotations (equipped with perfect interpretation)

Use CTRL +F to search ~~~~

@springBootApplication: declare that SpringBoot will automatically configure the program as necessary. This configuration is equivalent to: @Configuration, @EnableAutoConfiguration, and @ComponentScan are configured.

ResponseBody: indicates that the return result of this method is directly written to the HTTP response body. This method is used to obtain data asynchronously and build RESTful apis. After @requestMapping is used, the return value is usually interpreted as a jump path. After @esponSeBody is added, the return value is not interpreted as a jump path and is written directly to the HTTP Response Body. So if you get json data asynchronously, and you add @responseBody, it will return json data directly. This annotation is typically used in conjunction with @requestMapping.

@Controller: Defines the Controller class. In spring projects, the Controller is responsible for forwarding URL requests from the user to the corresponding service layer. Usually this annotation is in the class, and usually methods need to be annotated with @requestMapping.

@restController: A collection of annotated control-layer components such as actions in Struts, @responseBody, and @Controller.

@requestMapping: Provides routing information that maps urls to specific functions in the Controller.

@enableAutoConfiguration: SpringBoot Auto-Configuration: Try to automatically configure your Spring application based on the JAR dependencies you add. For example, if HSQLDB exists in your CLASspath and you don’t manually configure any database connection Beans, we will automatically configure an in-memory database. You can add the @EnableAutoConfiguration or @SpringBootApplication annotation to an @Configuration class to select automatic Configuration. If you find specific auto-configuration classes applied that you don’t want, you can disable them using the exclusion attribute of the @enableAutoConfiguration annotation.

@ComponentScan: automatically discovers scanned components for this class. If you scan a class with @Component, @Controller, @Service, etc., and register it as a Bean, you can automatically collect all Spring components, including the @Configuration class. We often use the @ComponentScan annotation to search for Beans, combined with the @AutoWired annotation to import. All Spring components can be collected automatically, including the @Configuration class. We often use the @ComponentScan annotation to search for Beans, combined with the @AutoWired annotation to import. If not, Spring Boot scans for classes that use @service, @repository annotations in the Boot package and its children.

@Configuration: Equivalent to a traditional XML Configuration file. If some third-party libraries require an XML file, it is recommended that the @Configuration class be used as the main Configuration class of the project — the XML Configuration file can be loaded using the @ImportResource annotation.

@import: Used to Import other configuration classes.

ImportResource: Used to load XML configuration files.

Autowired: Automatically import dependent beans

@service: Generally used to modify components in the Service layer

@ the Repository: Using the @Repository annotation ensures that DAO or Repositories provides an exception translation. The DAO or Repositories class modified by this annotation will be found and configured by ComponetScan without providing an XML configuration entry for them.

@beans: Annotating @beans is equivalent to beans configured in XML.

@value: Injects the Value of the Spring Boot Application. properties configured property. Sample code:

Inject @inject: Equivalent to the default @autowired, but without the required attribute;

@Component: Component annotation. This annotation can be used when components are difficult to categorize.

@bean: equivalent to XML, on top of a method, not a class, meaning to generate a Bean and hand it over to Spring to manage.

AutoWired: Automatically import dependent beans. ByType way. The configured Bean is used to complete the assembly of attributes and methods. It can annotate class member variables, methods and constructors to complete the work of automatic assembly. When (required=false) is added, no error is reported even if the bean is not found.

@qualifier: When there are multiple beans of the same type, you can specify it as @qualifier (” name “). Used with @autowired. In addition to being injected by name, the @qualifier Qualifier provides more fine-grained control over how candidates are selected, as follows:

@resource (name= “name”,type= “type”) : byName is the default if there is no parentheses. Same thing with @autowired.

The list of comments is as follows

@SpringBootApplication: includes @ComponentScan, @Configuration, and @EnableAutoConfiguration annotations. Among them

@ComponentScan: Have Spring Boot scan the Configuration class and add it to the application context.

@configuration: XML Configuration file equivalent to Spring; You can check type safety using Java code.

@enableAutoConfiguration: Automatic configuration.

@componentscan: ComponentScan to automatically discover and assemble some beans.

The @Component can be used in conjunction with CommandLineRunner to perform some basic tasks after the program is started.

@restController: Annotation is a combination of @Controller and @responseBody, indicating that this is a Controller bean and that the return value of the function is inserted directly into the BODY of the HTTP response. It is a REST-style Controller.

Autowired: Automatic import.

@pathvariable: Gets parameters.

JsonBackReference: Solve the nested external chain problem.

@ RepositoryRestResourcepublic: cooperate with spring – the boot – starter – data – rest.

JPA notes

@entity: @table (name= “) : indicates that this is an Entity class. These two annotations are usually used together, but @table can be omitted if the Table name is the same as the entity class name

MappedSuperClass: for an entity that is identified as a superclass. Attribute subclasses of the parent class can be inherited.

NoRepositoryBean: Normally used as a repository for the parent class. With this annotation, Spring will not instantiate the repository.

@column: If the field name is the same as the Column name, it can be omitted.

@id: indicates that the attribute is the primary key.

@ GeneratedValue (strategy = GenerationType SEQUENCE, the generator = “repair_seq”) : Indicates that the primary key generation policy is SEQUENCE (Auto, IDENTITY, or native). Auto indicates that the service can be switched among multiple databases. The sequence name is REPAIR_SEq.

@sequenceGeneretor (Name = “REPAIR_SEQ, sequenceName =” SEQ_REPAIR “, allocationSize = 1) : Name is the name of sequence, so that sequenceName is the name of the database sequence. The two names can be the same.

@TRANSIENT: indicates that this attribute is not a mapping to a field of a database table and will be ignored by the ORM framework. If a property is not a field mapping of a database table, it must be marked as @TRANSIENT; otherwise, the ORM framework defaults to annotating it as @BASIC. @BASIC (fetch= fetchtype.lazy) : tag that specifies how entity attributes are loaded

JsonIgnore: Some properties of Java bean are ignored during JSON serialization, which affects serialization and deserialization.

@joinColumn (name= “loginId”) : One-to-one: indicates the foreign key that points to another table in this table. One-to-many: another table points to the foreign key of this table.

@onetoone, @onetomany, @manytoone: Corresponds to one-to-one, one-to-many, many-to-one in hibernate configuration files.

4. SpringMVC annotations

@requestMapping: @requestMapping (/path) indicates that the controller processes all UR L requests of /path. RequestMapping is an annotation to handle request address mapping, which can be used on a class or method.

Used on a class, this address is used as the parent path for all methods in the class that respond to requests. This annotation has six attributes:

  • Params: Specifies that the request must contain some parameter values for this method to process.
  • Headers: Specifies that the request must contain some specified header value before the method can process the request.
  • Value: Specifies the actual address of the request, which can be the URI Template pattern
  • Method: Specifies the method type of the request, such as GET, POST, PUT, and DELETE
  • Consumes: specify the processing request of Content Type (the content-type), such as application/json, text/HTML.
  • Produces: Specifies the content type returned, only if the specified type is in the (Accept) type in the Request header

RequestParam: used in front of method arguments.

@requestParam String a =request.getParameter(" a ").Copy the code

@pathvariable: PathVariable.

The arguments must be the same as the names in braces.

5. Global exception handling

@ControllerAdvice: contains @Component. It can be scanned. Uniformly handle exceptions.

ExceptionHandler (exception.class) : Used above a method to indicate that the following method is executed when this Exception is encountered.

Vi. Specific configuration analysis and use environment in the project

@ MappedSuperclass:

  1. The @mappedsuperClass annotation is used on the parent class to identify the parent class
  2. The class identified by @mappedSuperClass means that it cannot be mapped to a database table because it is not a complete entity class, but it has attributes that can be mapped to the database table used by its subclass pairs
  3. Classes identified by @mappedSuperClass cannot have an @Entity or @table annotation

@ the Column:

\1. The @Column annotation is required when the attribute of the entity is not named in the Column of the database table it maps to. This attribute is usually preceded by the attribute declaration statement of the entity, and can also be used with the @ID annotation.

The common attribute of the 2.@Column annotation is name, which is used to set the column name of the mapped database table. In addition, the annotation also contains several other attributes, such as Unique, Nullable, Length, Precision, and so on. Details are as follows:

  • Name attribute: The name attribute defines the name of the field that the annotated field corresponds to in the database table
  • Unique attribute: The unique attribute indicates whether the field is a unique identifier. The default is false. If a field in the Table requires a unique identifier, you can use either this tag or @uniqueconstraint in the @TABLE annotation
  • Nullable property: The Nullable property indicates whether the field can be null. The default value is true
  • Insertable property: The insertable property indicates whether the value of the field needs to be inserted when the “INSERT” statement is used to INSERT data
  • Updateable property: The updateable property indicates whether the value of the field needs to be updated when the “UPDATE” statement is used to insert data
  • Insertable and Updateable properties: Typically used for read-only properties, such as primary and foreign keys, these fields are automatically generated
  • ColumnDefinition property: The columnDefinition property is the SQL statement created for the columnDefinition field when a table is created. The columnDefinition property is used when the Entity is used to generate the table definition. If the table has been created in the database, the columnDefinition property is unnecessary
  • Table property: The table property defines the name of the table that contains the current field
  • Length attribute: The length attribute indicates the length of a field. This attribute is valid only when the field type is VARCHAR. The default value is 255 characters
  • Precision and Scale: The precision and scale attributes together represent precision. When the field type is double, precision represents the total length of the value, and scale represents the number of decimal places

Details are as follows:

  1. A double is mapped to a double in the database. The precision and scale attributes are not valid
  2. Type double If the columnDefinition property specifies that the numeric type is decimal and the precision is specified, the columnDefinition prevails
  3. The BigDecimal type is mapped to the Decimal type in the database, and the precision and scale attributes are valid
  4. The precision and scale attributes are valid only in BigDecimal types

ColumnDefinition property of the 3.@Column annotation: indicates the actual type of the field in the database. Generally, ORM framework can automatically determine the type of the field in the database according to the attribute type, but for the Date type, it is still unable to determine whether the field type in the database is Date,TIME or TIMESTAMP. In addition, the default mapping type for String is VARCHAR, if you want to map String to a BLOB or TEXT field type for a particular database.

The 4.@Column annotation can also precede the getter method of a property

@getter and @setter (Lombok)

@setter: annotation on property; Provides the setting method for the property @getter: annotates on the property; Provide getting methods for properties

  • @data: Annotation on class; Provides getting and setting methods for all attributes of a class, as well as equals, canEqual, hashCode, and toString methods
  • @setter: annotation on property; Provide the setting method for the property
  • Getter: annotate a property; Provide getting methods for properties
  • @log4j2: Annotation on class; Provide the class with a log4j log object with the property log, similar to the @log4j annotation
  • NoArgsConstructor: Annotation on the class; Provides a constructor with no arguments for the class
  • AllArgsConstructor: Annotation on class; Provide a full-parameter constructor for the class
  • EqualsAndHashCode: By default, all non-transient and non-static fields are used to generate equals and Hascode methods, and you can specify which attributes to use.
  • @toString: Generates the toString method. By default, it prints the class name, all the attributes, and the attributes are printed in order, separated by commas.
  • NoArgsConstructor, @requiredargsconstructor and @allargsconstructor NoArgsConstructor, @requiredargsconstructor and @allargsconstructor NoArgsConstructor, @requiredargsconstructor and @allargsconstructor No parameter constructor, partial parameter constructor, full parameter constructor
  • @nonNULL: Annotation on a property, if annotated, must not be Null
  • @val: Annotation in the property, if the annotation, is set to final type, check the source code comments know

As you perform various persistence methods, the state of the entity changes, and the change in state triggers different lifecycle events. These events can use different annotations to indicate the callback function when they occur.

@ javax.mail. Persistence. PostLoad: after loading.

Before @ javax.mail. Persistence. PrePersist: persistence.

After @ javax.mail. Persistence. PostPersist: persistence.

@ javax.mail. Persistence. PreUpdate: before updating.

@ javax.mail. Persistence. PostUpdate: updated.

@ javax.mail. Persistence. PreRemove: delete the former.

@ javax.mail. Persistence. PostRemove: after deletion.

1) Database query

The @postload event is triggered when:

After an entity is loaded by executing the EntityManager.find() or getreference() method.

After the JPQL query is executed.

After the entityManager.refresh () method is called.

2) Database insert

@prepersist and @postpersist events occur during the insertion of the entity object into the database:

The @prepersist event occurs immediately after the persist() method is called, before the data is actually inserted into the database.

The @postpersist event occurs after the data has been inserted into the database.

3) Database update

The @preUpdate and @postUpdate events are triggered by the update entity:

The @preUpdate event is emitted before the entity’s state is synchronized to the database, before the data is actually updated to the database.

The @PostUpdate event is fired after the entity’s state is synchronized to the database, which occurs when the transaction commits.

4) Database deletion

The @PRERemove and @Postremove events are triggered by deleting entities:

The @PRERemove event is triggered before the entity is removed from the database, that is, when the remove() method is called, before the data is actually removed from the database.

The @Postremove event is emitted after the entity is deleted from the database.