Environment configuration of JPA wrong posture in spring boot series


Environment configuration of JPA wrong posture in spring boot series

Environment configuration of JPA wrong posture in 191218 spring boot series

Back to the tutorial of JPA, this article is from a simple project that needs to read and write dB. I thought it would be easier to use JPA directly, but I found many pitfalls in the actual development process. This article is the first article of the wrong posture, the repository interface can not inject questions

<!– more –>

1. Configuration issues

A new JPA project combined with springboot can be easily implemented, but in some environments, you may encounter the problem that the custom JPA repository interface cannot be injected

1. Basic configuration

In the spring boot environment, you need topom.xmlIn the file, specify the following two dependencies


Next, you need to modify the configuration file(application.properties), specify the configuration information of the database

## DataSource


2. Case recurrence of injection failure

First, add a new table in MySQL’s story library

CREATE TABLE `meta_group` (
  `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;

Then define the entity corresponding to this table

@Table(name = "meta_group")
public class MetaGroupPO {
    @Column(name = "`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;

Corresponding repository interface

public interface GroupJPARepository extends JpaRepository<MetaGroupPO, Integer> {

    List<MetaGroupPO> findByProfile(String profile);

    MetaGroupPO findByGroupAndProfileAndDeleted(String group, String profile, Integer deleted);

    @Query("update MetaGroupJpaPO m set m.desc=?2 where m.id=?1")
    int updateDesc(int groupId, String desc);

    @Query("update MetaGroupJpaPO m set m.deleted=1 where m.id=?1")
    int logicDeleted(int groupId);

A simple data operation encapsulation classGroupManager


public class GroupManager {
    private GroupJPARepository groupJPARepository;

    public MetaGroupPO getOnlineGroup(String group, String profile) {
        return groupJPARepository.findByGroupAndProfileAndDeleted(group, profile, 0);

    public Integer addGroup(String group, String profile, String desc) {
        MetaGroupPO jpa = new MetaGroupPO();
        Timestamp timestamp = Timestamp.from(Instant.now());
        MetaGroupPO res = groupJPARepository.save(jpa);
        return res.getId();

The next point is that when our startup class is not outside, there may be problems; the project structure is as follows

Environment configuration of JPA wrong posture in spring boot series

Let’s look at the configuration class and the wrong startup application class

public class JpaCaseAutoConfiguration {

public class ErrorApplication {

    public static void main(String[] args) {


Direct start failed. The exception is as shown in the figure below. The prompt is not foundGroupJPARepositoryThis bean, in the normal startup mode, will be used by spring to generate a proxy class for us; obviously, it is not generated here

Environment configuration of JPA wrong posture in spring boot series

3. Case analysis

The case above may be a little extreme. Generally speaking, we will put the project startup class in the outermost layer. Basically, the project structure above is not likely to appear, so what’s the use of analyzing this case?

A typical case

  • We put the logic of DB operation in a module (such as dao.jar )In the package
  • Then there is a module to start, which is introduced through Maven dao.jar
  • This is the Default scan range for the portal, and may not contain dao.jar Therefore, it is likely to lead to injection failure

4. Solutions

So how to solve this problem?

In the configuration class, add two annotationsEnableJpaRepositoriesAndEntityScan, and make the corresponding package path

public class TrueJpaCaseAutoConfiguration {

Then test again

public class TrueApplication {

    public TrueApplication(GroupManager groupManager) {
        int groupId =  groupManager.addGroup ("true group", "dev", "write correctly!!!");
        System.out.println("add groupId: " + groupId);
        MetaGroupPO po = groupManager.getOnlineGroup("true-group", "dev");

    public static void main(String[] args) {

Environment configuration of JPA wrong posture in spring boot series

5. Summary

Finally, when we find that the JPA repository cannot be injected, it is generally because the interface is no longer in our scanning path and needs to pass the@EntityScanAnd@EnableJpaRepositoriesTo specify

(because of the length, other problems are split into other blogs)

2. Others

0. Project

  • 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
  • Save the specified ID of JPA in 191119 spring boot series
  • Project: https://github.com/liuyueyi/spring-boot-demo
  • module: https://github.com/liuyueyi/spring-boot-demo/blob/master/spring-boot/102-jpa-errorcase

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

  • A grey blog personal blog https://blog.hhui.top
  • A grey blog spring special blog http://spring.hhui.top

Environment configuration of JPA wrong posture in spring boot series

Recommended Today

The use of springboot Ajax

Ajax overview What is Ajax? data Ajax application scenarios? project Commodity system. Evaluation system. Map system. ….. Ajax can only send and retrieve the necessary data to the server, and use JavaScript to process the response from the server on the client side. data But Ajax technology also has disadvantages, the biggest disadvantage is that […]