【问题标题】:Exception: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:异常:上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.BeanCreationException:
【发布时间】:2020-05-03 15:01:06
【问题描述】:

我正在尝试建立一对多关系(表 EmployeeEntity 和 AddressEntity),但是当我构建时出现错误。

AddressEntity 类

@Data
@EqualsAndHashCode(exclude = "eeEntity")

public class AddressEntity {
..

@OneToMany(mappedBy = "addressEntity", targetEntity = com.howtodoinjava.demo.model.AddressEntity.class,cascade = CascadeType.ALL)

private Set<EmployeeEntity> eeEntity;

public AddressEntity(String city, EmployeeEntity... eeEntity) {
    this.city = city;
    this.eeEntity = Stream.of(eeEntity).collect(Collectors.toSet());
    this.eeEntity.forEach(x -> x.setAddressEntity(this));
}
---------

EmployeeEntity 类

@Data
@Entity
public class EmployeeEntity {
...
    @ManyToOne(targetEntity = com.howtodoinjava.demo.model.AddressEntity.class)
private AddressEntity addressEntity;

public AddressEntity getAddressEntity() {
    return addressEntity;
}

public void setAddressEntity(AddressEntity addressEntity) {
    this.addressEntity = addressEntity;

错误: 2020-01-17 00:01:24.401 WARN 4890 --- [main] ConfigServletWebServerApplicationContext:上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.BeanCreationException:创建名称为“entityManagerFactory”的bean时定义在类路径资源[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:init方法调用失败;嵌套异常是 org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.howtodoinjava.demo.model.AddressEntity.eeEntity 中的 com.howtodoinjava.demo.model.AddressEntity.addressEntity

org.springframework.beans.factory.BeanCreationException:在类路径资源 [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class] 中定义名称为“entityManagerFactory”的 bean 创建错误:调用 init 方法失败;嵌套异常是 org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.howtodoinjava.demo.model.AddressEntity.eeEntity 中的 com.howtodoinjava.demo.model.AddressEntity.addressEntity

有人能帮我理解为什么会这样吗?

【问题讨论】:

  • 您在 AddressEntity 类上缺少@Entity 注释
  • 我也试过了,但没有运气。

标签: hibernate spring-data-jpa one-to-many


【解决方案1】:

试试下面的代码sn-p,

在 AddressEntity 类中,

@OneToMany(mappedBy = "addressEntity", targetEntity = com.howtodoinjava.demo.model.AddressEntity.class,cascade = CascadeType.ALL)
private Set<EmployeeEntity> eeEntity;

在 EmployeeEntity 类中,

@ManyToOne
@JoinColumn(name="ADDRESS_ID", nullable=false)
private AddressEntity addressEntity;

其中 ADDRESS_ID 可以是 AddressEntity 的主键。

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2016-08-02
    • 2015-12-04
    • 2018-01-26
    • 2019-08-29
    • 2020-06-13
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多