Implementation of Database Entity Definition for Spring Boot

Time:2019-10-9

Articles Series

  • Hello World of Sprint Boot
  • Introduction to Program Structure Design of Sprint Boot

Preface

This article begins with code practice, and the system design starts from bottom to top. So this article first introduces how to realize the design and implementation of database table entity class.

The persistence layer framework of SpringBook database is mainly divided into two kinds of architecture modes, that is to say, the persistence layer framework of SpringBook database is based on the persistence layer framework of SpringBook database.JDBC TemplateRepresentatives of the SQL class and theSpring Data JPARepresented ORM object class. Among them:

Spring Data JPA is a JPA application framework encapsulated by Spring based on ORM framework and JPA specification. It enables developers to access and operate data with minimal code. It provides common functions including add, delete, modify and check, and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency! Spring data JPA frees us from the operation of DAO layer. Basically, all CRUDs can rely on it to implement. After writing a warehouse interface and inheriting Jpa Repository, we can achieve the most basic function of adding, deleting and modifying.

in use@EntityPerform persistent operations on entity classes whenJPAWhen @Entity annotation is detected in our entity class, table structure information corresponding to association mapping will be generated in the database, so a bottom-level design for this project is implemented.@EntityAnnotated Book object definition is enough.

Before starting the project, follow the program structure design of Sprint Boot in the previous article [Introduction to Zero Series-1]. The background program structure is explained and the corresponding directory is established.

Control Layer: Front-end Routing and Back-end Processing Relation Processing, Directory: Controller
Data Service Layer: Customize the method of accessing database, Directory: Service
Data Access Layer: Implementing Universal Database Access Function, JPA Scheme of Spring Data, Directory: Dao
Data Entity Layer: Define attribute methods for database tables, directory: Domain

According to the structure, we need to write the project table entity class in the Domain directory, right-clickDomainFolder,New->Java Class


Writing Entity Classes

1. New constructionBookclass

package com.arbboter.demolibrary.Domain;
   
   import javax.persistence.Entity;
   import javax.persistence.Table;
   
   /**
    *@ Entity annotates that this class is a database table entity class, which JPA can automatically scan and recognize.
    *@ Table annotates table information, where name specifies the table name
    */
   @Entity
   @Table(name = "library_book")
   public class Book{
   }

Note that the added classes need to be used@EntityAnnotations, where@TableOptionally, the generated table name and class name are not configured by default if they are not used in the above classes@TableThen the corresponding table name of this class isbook

2. Add table field information

public class Book{
       /**
        * ID, the only primary key, press Alt + Enter to quickly import the import
        */
       @Id
       @GeneratedValue
       private Integer id;
   
       /**
        * Title of the book
        */
       private String name;
   
       /**
        * Author
        */
       private String author;
   
       /**
        * Cover
        */
       private String image;
   }

@IdAnnotations are used to declare that the attributes of an entity class are mapped to the primary key columns of the database. The attributes are usually placed before the attribute declaration statement and can be written on a separate line as well as on the same line as the declaration statement.

@GeneratedValueGeneration strategies for annotating primary keys are specified by the strategy attribute. By default, JPA automatically selects a primary key generation strategy that best suits the underlying database: SqlServer corresponds to identity, MySQL corresponds to auto increment.

  • TABLE: Use a specific database table to save the primary key.
  • SEQUENCE: The primary key is generated from the sequence of the underlying database, provided that the database supports the sequence.
  • IDENTITY: Primary keys are automatically generated by the database (mainly auto-growing)
  • AUTO: The primary key is controlled by the program.

The default value of the strategy attribute for this annotation isGenerationType.AUTO

3. Use IDEA to add automaticallygetter setter toStringMethod

@Entity
   @Table(name = "library_book")
   public class Book{
       /**
        * Attributes are not listed here
        */
   
       /**
        * Press Alt + Insert or right-click in the blank of this file to select Generate...
        * Automatic Generation of getter and setter and toString Method
        */
       public Integer getId() {
           return id;
       }
   
       public void setId(Integer id) {
           this.id = id;
       }
   
       public String getName() {
           return name;
       }
   
       public void setName(String name) {
           this.name = name;
       }
   
       public String getAuthor() {
           return author;
       }
   
       public void setAuthor(String author) {
           this.author = author;
       }
   
       public String getImage() {
           return image;
       }
   
       public void setImage(String image) {
           this.image = image;
       }
   
       @Override
       public String toString() {
           return "Book{" +
                   "id=" + id +
                   ", name='" + name + '\'' +
                   ", author='" + author + '\'' +
                   ", image='" + image + '\'' +
                   '}';
       }
   }

SuggestionsAlt+InsertOr right-click in the blank of this fileGenerate...Automatic GenerationgetterandsetterandtoStringMethod, wheretoStringEasy to export and consult.

4. Start the test

At this point, the main function is started and the program starts normally, but when we look at the database, we can find the database tables.library_bookIt’s not automatically generated, because we haven’t customized JPA configuration yet.

Here we first configure the configuration of JPA, the SQL Server 2008 database used in this project, in theapplication.propertiesAdd the following configuration information to the configuration file:

# JPA configuration
spring.jpa.database=sql_server
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2008Dialect

It is suggested that all the above configuration items should be set up. I did not configure them in the learning process.spring.jpa.database-platformItem, resulting in project startup failure. To configurespring.jpa.hibernate.ddl-autoValuation means:

  • Ddl-auto: create – Every time you run the program, no tables will be created, and the data in the tables will be emptied.
  • Ddl-auto: create-drop — Clear the table at the end of each program
  • Ddl-auto: update – Every time you run a program, no table will create a new table, the data in the table will not be empty, only updated.
  • Ddl-auto: validate – Running programs verify that data and database field types are the same, and that different types of errors will be reported

After adding this configuration, start the program again, and we can see output like this in the output bar:

2019-05-14 12:09:34.977  INFO 115652 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2008Dialect
Hibernate: create table library_book (id int not null, author varchar(255), image varchar(255), name varchar(255), primary key (id))

From the log, we can see that the program has been created automatically.bookEntity class, can be verified in the database found that the table has been created OK.


Notes

  • @ Table – Mapping Table Name

    @ Table annotations are used to identify the corresponding relationship between entity classes and data tables, and the default and class names are the same.

  • @ Id – primary key
  • @ GeneratedValue (strategy = GenerationType. IDENTITY) – Automatic incremental generation
  • @ Column (name = dict_name, column Definition = “varchar (100) COMMENT’dictionary name’) – field name, type, annotation

    Column annotation identifies the corresponding relationship between attributes in entity classes and fields in data tables, all of which are optional attributes:

    • The name attribute defines the name of the field corresponding to the annotated field in the database table.
    • The unique attribute indicates whether the field is a unique identifier, defaulting to false. If a field in a table needs a unique identifier, you can use either the tag or @UniqueConstraint in the @Table tag.
    • The nullable attribute indicates whether the field can be null by default, true. If the @NotNull annotation in the validation class is used in the attribute, the attribute can not be written.
    • The insertable attribute indicates whether the value of the field needs to be inserted when the “INSERT” script is used to insert data.
    • The updatable attribute indicates whether the value of the field needs to be updated when inserting data using the “UPDATE” script. Insertable and updatable attributes are generally used for read-only attributes, such as primary and foreign keys. The values of these fields are usually automatically generated.
    • The column nDefinition attribute represents the SQL statement created by this field when creating a table, which is generally used when generating table definitions through Entity. If this property is not specified, the default type is usually used to build the table. If you need to customize the type of the table, you can set it in this property. (That is to say, if the table in DB has been built, it is not necessary to use this property.)
    • The table attribute defines the name of the table that contains the current field.
    • The length attribute represents the length of the field, which is valid when the field type is varchar, defaulting to 255 characters.
    • Precision and scale attributes denote accuracy. When the field type is double, precision denotes the total length of the value, and scale denotes the number of decimal points.
  • @ Update Timestamp – Update time automatically
  • @ Creation Timestamp – Automatic update time at creation
  • @ Version – version number, automatically add 1 when updating

Concluding remarks

This chapter records the simple implementation of database entity class, and throughapplication.propertiesTo configureJPAThe database configuration items enable the program to automatically associate and operate the database tables after running.

In the next chapter, we will introduce the related content of CRUD operation. Please continue to pay attention to it.