springboot整合jpa踩过的坑

348 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第26天,点击查看活动详情

1.  没有扫描到jpa注解的实体类

异常信息:

spring boot jpa-java.lang.IllegalArgumentException: Not a managed type

异常原因:

造成这种异常的原因是因为没有扫描到jpa注解的实体类

解决方法:在启动类加上扫描实体类的注解@EntityScan(basePackages = {"com.jpa.model"})

2. 属性名对不上

异常信息:

org.springframework.data.mapping.PropertyReferenceException: No property name found for type User

这种原因是jpa的JpaRepository的方法名称是通过实体类的属性名称来进行查询的

解决方法:检查方法名称中的属性名称和对应的实体类的属性名称是否对应

3. 没有主键

异常信息:

No Identifier specified for entity

异常原因:

这种问题主要是实体类没有主键造成的,继承JpaRepository的时候需要指定实体类和主键,在扫描实体类的时候如果实体类没有主键注解的话,springboot就会报错

解决方法: 实体类对应的数据库表添加主键,并在主键上加注解@Id

4. 依赖循环

异常信息:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion(StackOverflowError);nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain:xxxxxx

从异常中信息能够看出在转化为json的过程中产生了死循环,把A类转化为json的时候,A类中做了B类的关联映射,而B类中又管理了A类,这样就产生了json转化死循环,究其原因是因为在双向关联的时候没有指定哪一方来维护关联关系,所以才会产生这样的原因,有两种解决方法:

①在一方的的get方法中加上@JsonBackReference注解

②指定维护关系,

(1)可以在 one 方指定 @OneToMany 注释并设置 mappedBy 属性,以指定它是这一关联中的被维护端,many 为维护端。

例:

@OneToMany(fetch = FetchType.LAZY ,targetEntity = DeviceEntity.class,mappedBy = "areaId")

(2)在双向的一对一关联中,需要在关系被维护端(inverse side)中的 @OneToOne 注释中指定 mappedBy,以指定是这一关联中的被维护端

TemplateEntity.java

@OneToOne(fetch = FetchType.LAZY ,cascade = CascadeType.ALL, mappedBy = "templateEntity")  
public ConfigEntity getConfigEntity() {  
    return configEntity;
}

ConfigEntity.java

@JoinColumn(name = "template_id" , insertable = false , updatable = false)  
public TemplateEntity getTemplateEntity() {  
    return templateEntity;  
}

(mappedBy属性定义了此类为双向关系的维护端,注意:mappedBy 属性的值为此关系的另一端的属性名。)

5. 没有getter、setter

异常信息:

org.hibernate.MappingException: Could not determine type for: xxxxxx

异常原因及解决方案:

这是因为在实体类中建立关联关系的时候,要把关联关系注解加在getter方法,在属性或setter方法上就会出现这样情况