Entity mapping of spring boot series JPA wrong posture

Time:2020-3-6

Entity mapping of spring boot series JPA wrong posture

Entity mapping of spring boot series JPA wrong posture

This is the second part of JPA error usage posture. Is there any other pit besides hump naming mapping to underline for the mapping relationship between Java POJO class and database table structure?

<!– more –>

1. Mapping problem

1. Basic configuration of the project

First, build the basic springboot + JPA project. The version of springboot we use is2.2.1.RELEASE, MySQL version 5+

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

Project profileapplication.properties

## DataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Table structure

CREATE TABLE `meta_group` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `Group ` varchar (32) not null default 'comment' Group ',
  `Profile ` varchar (32) not null default '' comment 'profile is currently used in the application environment with the value of dev / test / Pro',
  `Desc ` varchar (64) not null default '' comment 'explanation',
  `Deleted ` int (4) not null default '0' comment '0 means valid 1 means invalid',
  `Create "time ` timestamp not null default current" timestamp comment 'creation time',
  `Update ﹣ time ` timestamp not null default current ﹣ timestamp on update current ﹣ timestamp comment 'modification time',
  PRIMARY KEY (`id`),
  KEY `group_profile` (`group`,`profile`)
)Engine = InnoDB auto [increment = 6 default charset = utf8mb4 comment = 'business configuration grouping table';

2. Error case

Java variable naming recommends the hump naming method, so the underline method of fields in the database needs to be associated with mapping. We know that we can use the@ColumnThe annotation is used for processing, so it has the following writing method

@Data
@Entity
@Table(name = "meta_group")
public class ErrorMetaGroupPo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "group")
    private String group;

    @Column(name = "profile")
    private String profile;

    @Column(name = "desc")
    private String desc;

    @Column(name = "deleted")
    private Integer deleted;

    @Column(name = "create_time")
    private Timestamp createTime;

    @Column(name = "update_time")
    private Timestamp updateTime;
}

It can be seen from the naming that the above case is wrong, so what is the problem?

First write a corresponding repository to measure it

public interface ErrorGroupJPARepository extends JpaRepository<ErrorMetaGroupPo, Integer> {
}

Test code

@Component
public class GroupManager {
    @Autowired
    private ErrorGroupJPARepository errorGroupJPARepository;

    public void test() {
        String group = UUID.randomUUID().toString().substring(0, 4);
        String profile = "dev";
        String desc = "test JPA exception case!";
        try {
            int id = addGroup1(group, profile, desc);
            System.out.println("add1: " + id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Integer addGroup1(String group, String profile, String desc) {
        ErrorMetaGroupPo jpa = new ErrorMetaGroupPo();
        jpa.setGroup("add1: " + group);
        jpa.setDesc(desc);
        jpa.setProfile(profile);
        jpa.setDeleted(0);
        Timestamp timestamp = Timestamp.from(Instant.now());
        jpa.setCreateTime(timestamp);
        jpa.setUpdateTime(timestamp);
        ErrorMetaGroupPo res = errorGroupJPARepository.save(jpa);
        return res.getId();
    }
}

Entity mapping of spring boot series JPA wrong posture

From the output results, the SQL exception is prompted, why?

  • Group and desc are keywords, which need to be enclosed with back quotes when spelling SQL

3. Correct posture I

The first is to use posture correctly, directly@columnIn the name of, enclose it with back Quotes

@Data
@Entity
@Table(name = "meta_group")
public class MetaGroupPO {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "`group`")
    private String group;

    @Column(name = "`profile`")
    private String profile;

    @Column(name = "`desc`")
    private String desc;

    @Column(name = "`deleted`")
    private Integer deleted;

    @Column(name = "`create_time`")
    private Timestamp createTime;

    @Column(name = "`update_time`")
    private Timestamp updateTime;
}

4. Correct posture II

In addition to the above case, there is another general way to implement customizedPhysicalNamingStrategy, implement field mapping

For example, we customizeJpaNamingStrategyStandardImplInherited from defaultPhysicalNamingStrategyStandardImplPolicy, and then in the field name, add a back quote to the field name of the package without quotation marks

public class JpaNamingStrategyStandardImpl extends PhysicalNamingStrategyStandardImpl {
    @Setter
    private static int mode = 0;

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
        if (mode == 1) {
            if (name.isQuoted()) {
                return name;
            } else {
                return Identifier.toIdentifier("`" + name.getText() + "`", true);
            }
        } else {
            return name;
        }
    }
}

Note that the configuration file needs to be modified to use the mapping policy above(application.properties)

spring.jpa.hibernate.naming.physical-strategy=com.git.hui.boot.jpacase.strategy.JpaNamingStrategyStandardImpl

Test case

@SpringBootApplication
public class Application {
    public Application(GroupManager groupManager) {
        groupManager.test();
    }

    public static void main(String[] args) {
        JpaNamingStrategyStandardImpl.setMode(1);
        SpringApplication.run(Application.class, args);
    }
}

@Component
public class GroupManager {
    @Autowired
    private ErrorGroupJPARepository errorGroupJPARepository;

    @Autowired
    private GroupJPARepository groupJPARepository;


    public void test() {
        String group = UUID.randomUUID().toString().substring(0, 4);
        String profile = "dev";
        String desc = "test JPA exception case!";
        try {
            int id = addGroup1(group, profile, desc);
            System.out.println("add1: " + errorGroupJPARepository.findById(id));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            int id2 = addGroup2(group, profile, desc);
            System.out.println("add2: " + groupJPARepository.findById(id2));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Integer addGroup1(String group, String profile, String desc) {
        ErrorMetaGroupPo jpa = new ErrorMetaGroupPo();
        jpa.setGroup("add1: " + group);
        jpa.setDesc(desc);
        jpa.setProfile(profile);
        jpa.setDeleted(0);
        Timestamp timestamp = Timestamp.from(Instant.now());
        jpa.setCreateTime(timestamp);
        jpa.setUpdateTime(timestamp);
        ErrorMetaGroupPo res = errorGroupJPARepository.save(jpa);
        return res.getId();
    }

    public Integer addGroup2(String group, String profile, String desc) {
        MetaGroupPO jpa = new MetaGroupPO();
        jpa.setGroup("add2: " + group);
        jpa.setDesc(desc);
        jpa.setProfile(profile);
        jpa.setDeleted(0);
        Timestamp timestamp = Timestamp.from(Instant.now());
        jpa.setCreateTime(timestamp);
        jpa.setUpdateTime(timestamp);
        MetaGroupPO res = groupJPARepository.save(jpa);
        return res.getId();
    }
}

Output after execution:

Entity mapping of spring boot series JPA wrong posture

II. other

0. Project & related blog

Recommend Bo Wen

  • Building the basic environment of JPA
  • 190614 spring boot series new record using posture of JPA
  • 190623 spring boot series tutorial update usage posture of JPA
  • 190702 spring boot series tutorial: detailed explanation of delete using posture of JPA
  • 190717 spring boot series tutorial: basic chapter of detailed explanation of query usage posture in JPA
  • Environment configuration of JPA wrong posture in 191218 spring boot series

Source code

  • Project: https://github.com/liuyueyi/spring-boot-demo
  • Project: https://github.com/liuyueyi/spring-boot-demo/blob/master/spring-boot/102-jpa-errorcase 2

1. A grey blog

The best letter is not as good as the above. It’s just a one-of-a-kind remark. Due to the limited personal ability, there are inevitably omissions and mistakes. If you find a bug or have better suggestions, you are welcome to criticize and correct. Thank you very much

Here is a grey personal blog, recording all the blogs in study and work. Welcome to visit

  • One gray blog https://blog.hhui.top
  • Http://spring.hhui.top

Entity mapping of spring boot series JPA wrong posture

Recommended Today

Digital DP-902. Number combinations up to N

Problem Description Given an array digits of digits in non-decreasing order. A number you can write with digits[i] any number of times. For example, if digits = ['1','3','5'], we can write digits like '13', '551', and '1351315'. Returns the number of positive integers that can be generated that are less than or equal to the […]