JAVA 8
Spring Boot 2.5.3
MySQL 5.7.21
---
Note: this code uses org.projectlombok:lombok (the version is specified by Spring Boot).
catalogue
4.2. Do not use @ Column annotation
4.4. Creation time and last update time
4.7. Object type attribute JSON type (MySQL)
Spring Boot project database configuration:
Database configuration# MySQL on Ubuntu spring.datasource.url=jdbc:mysql://mylinux:3306/jpa?serverTimezone=Asia/Shanghai spring.datasource.username=springuser spring.datasource.password=ThePassword #spring.datasource.driver-class-name =com.mysql.jdbc.Driver # This is deprecated spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect # Open the SQL statement executed during use spring.jpa.show-sql: true
Entity classes are POJO objects, so the @ Data annotation of lombok is used.
1. Create entity class
Use @ Entity annotation (javax.persistence.Entity. Unless otherwise specified later, the annotations come from javax.persistence package).
@Entity @Data public class User {
The default creation table name is user (all lowercase). You can use the name attribute to specify the table name.
@Entity(name="user2") @Data public class User {
The two tables established in the above two cases are as follows:
2. Primary key id
Use @ Id annotation;
The @ GeneratedValue annotation is used to configure the auto increment strategy of the primary key;
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | id | bigint(20) | NO | PRI | NULL | auto_increment |
See GenerationType enumeration class for auto increment policy:
TABLE
SEQUENCE
IDENTITY
AUTO
For MySQL, not every (TODO) is supported.
3. Composite primary key
@PrimaryKeyJoinColumns and @ PrimaryKeyJoinColumn annotations.
4. General field
4.1. Use @ Column annotation
@Column(columnDefinition = "VARCHAR(100) NOT NULL") private String firstName; @Column(columnDefinition = "VARCHAR(100) NOT NULL") private String lastName; @Column(columnDefinition = "INT DEFAULT 0") private Integer age;
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | age | int(11) | YES | | 0 | | | first_name | varchar(100) | NO | | NULL | | | last_name | varchar(100) | NO | | NULL | |
In addition to the columnDefinition attribute used above, @ Column has other attributes for configuration.
@The name attribute of Column is used to customize the field name in the data table.
Question:
1) How to create a field when the columnDefinition is consistent with the configuration of other properties?
2) How to create a field when the configuration of columnDefinition conflicts with other properties?
4.2. Do not use @ Column annotation
// User.java private Integer property; private Float height; private Float weight; private String slogan;
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | height | float | NO | | NULL | | | weight | float | NO | | NULL | | | slogan | varchar(255) | YES | | NULL | | | property | int(11) | YES | | NULL | |
The Default values are NULL, and the String type is NULL by Default varchar(255).
4.3 enumeration type
// Enumeration class UserSex.java @Getter public enum UserSex { MALE(0, "MALE"), FEMALE(1, "FEMALE"); private int code; private String info; private UserSex(int code, String info) { this.code = code; this.info = info; } } // User.java // Do not use @ Column annotation private UserSex sex;
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | sex | int(11) | YES | | NULL | |
The type in the data table is int(11).
The actual stored data are: 0, 1
mysql> select distinct sex from user; +------+ | sex | +------+ | 0 | | 1 | +------+ 2 rows in set (0.00 sec)
4.4. Creation time and last update time
// User.java @Column(insertable = false, columnDefinition = "DATETIME DEFAULT NOW()") private Date createTime; @Column(insertable = false, updatable = false, columnDefinition = "DATETIME DEFAULT NOW() ON UPDATE NOW()") private Date updateTime;
After configuring as above, there is no need to set the values of these two fields when adding and updating records.
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | create_time | datetime | YES | | CURRENT_TIMESTAMP | | | update_time | datetime | YES | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
4.5,@Transient
Indicates that if the field is not stored, the field will not be created in the data table.
// User.java @Transient private String abcNotInDb;
Check the data table and find no corresponding fields, which is in line with expectations.
4.6. Object type attribute
For example, how to access the user's address, which includes provinces, cities and so on?
As follows: @ embedded is used in POJO objects and @ Embedded + @AttributeOverrides + @AttributeOverride is used in entity classes.
// Address.java 4 attributes @Data @Embeddable public class Address { /** * Postal Code */ @Column(updatable = false) private String zipCode; // Provincial and urban Level 3 // province private String province; // city private String city; // area private String district; } // User.java @Embedded @AttributeOverrides({ @AttributeOverride(name="zipCode", column = @Column(name = "address_zip_code")), @AttributeOverride(name="province", column = @Column(name = "address_province")), @AttributeOverride(name="city", column = @Column(name = "address_city")), @AttributeOverride(name="district", column = @Column(name = "address_district")) }) private Address address;
Effect in data sheet:
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | address_zip_code | varchar(255) | YES | | NULL | | | address_city | varchar(255) | YES | | NULL | | | address_district | varchar(255) | YES | | NULL | | | address_province | varchar(255) | YES | | NULL | |
Trial and error: when the entity class does not use each annotation, but only the address object, the data table field will also be generated, but there is no address prefix.
Add an address2 attribute:
// User.java private Address address2;
Four fields are added to the data table: from the blog Garden
4.7. Object type attribute JSON type (MySQL)
MySQL 5.7.8 starts to provide JSON types.
Note that the city, district, province and zip generated in section 4.6 need to be deleted before the test_ Code has four fields.
// User.java @Column(columnDefinition = "JSON") private Address jsonAddress;
Start project: no JSON found_ Address field. However, city, district, province and zip are generated_ Code and other four fields.
Failed!
Self test: add JSON type field to user table: success. From blog Garden
mysql> alter table user add json1 JSON; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> desc user; ... | json1 | json | YES | | NULL | | +------------------+--------------+------+-----+-------------------+-----------------------------+ 22 rows in set (0.00 sec)
It seems that JPA does not support the JSON type of MySQL.
Is it related to the following configuration? TODO
// application.properties spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
The method in reference document 3 is tested to add JSON type objects.
Add dependent packages in pom.xml:
<dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>2.4.3</version> </dependency>
Latest version Dependent package:
Copy the above Address to create the Address2 class, but remove its @ Embeddable annotation.
@Data //@Embedded / / JSON type needs to be deleted //public class Address2 implements Serializable {/ / the Serializable interface does not need to be implemented public class Address2 { /** * */ // private static final long serialVersionUID = 211030L; /** * Postal Code */ @Column(updatable = false) private String zipCode2; ... }
Entity class addition: from blog Garden
// User.java // The Address property is invalid. Four fields under Address will be created @Type(type = "json") @Column(columnDefinition = "json") private Address jsonAddress; // Address2 property, valid, will create JSON type field json_address2 @Type(type = "json") @Column(columnDefinition = "json") private Address2 jsonAddress2;
Some of the above comments are not from the javax.persistence package:
import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import com.vladmihalcea.hibernate.type.json.JsonStringType;
Start the project and modify the SQL log statement of the table: from the blog Garden
2021-10-30 10:58:15.409 INFO 19068 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect Hibernate: alter table user add column city varchar(255) Hibernate: alter table user add column district varchar(255) Hibernate: alter table user add column province varchar(255) Hibernate: alter table user add column zip_code varchar(255) Hibernate: alter table user add column json_address2 json
Effect in data table: from blog Garden
mysql> desc user; +------------------+--------------+------+-----+-------------------+-----------------------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+-------------------+-----------------------------+ | city | varchar(255) | YES | | NULL | | | district | varchar(255) | YES | | NULL | | | province | varchar(255) | YES | | NULL | | | zip_code | varchar(255) | YES | | NULL | | | json_address2 | json | YES | | NULL | |
>>>The full text is from the blog Garden
Reference documents
1,JPA object type attribute operation
Good article.
2,The spring boot + MySQL configuration supports json data format
At the time of publishing this article, I haven't taken a closer look. mybatis is used in it.
3,MySQL 5.7 json jpa_spring data jpa + mysql uses json type
Good article
4,