【问题标题】:Sping Boot AnnotationException - mappedBy reference an unknown target entity propertySpring Boot AnnotationException - mappedBy 引用未知的目标实体属性
【发布时间】:2021-11-12 11:22:30
【问题描述】:

我试图了解实体关系在 Spring Boot 中是如何工作的。为了理解它们,我正在尝试实现以下数据库架构

到目前为止,我已经以这种方式实现了实体

用户

@Entity // This tells Hibernate to make a table out of this class
public class User {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;

  private String name;

  private String email;

  private String passwordDigest;

  @OneToMany(mappedBy = "followerId")
  Set<User> followers;

  @OneToMany(mappedBy = "followedId")
  Set<User> follows;

  @OneToMany(mappedBy = "user")
  Set<Tweet> tweets;

  @Temporal(TemporalType.DATE)
  private Date createdAt;
  
  @Temporal(TemporalType.DATE)
  private Date updatedAt;

  // constructors, getters and setters

}

关系

@Entity
@Table(indexes = @Index(columnList = "follower_id, followed_id"))
class Relationship {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "user_id")
    User followerId;

    @ManyToOne
    @JoinColumn(name = "user_id")
    User followedId;

    @Temporal(TemporalType.DATE)
    Date createdAt;
    
    @Temporal(TemporalType.DATE)
    Date updatedAt;

    // constructors, getters and setters

}

推文

@Entity
public class Tweet {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    String content;

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    User user;

    // constructors, getters and setters
}

现在,在运行应用程序时出现以下错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.example.demo.entity.User.followerId in com.example.demo.entity.User.followers

这对我来说看起来很奇怪,因为我确定了这一点

@OneToMany(mappedBy = "followerId")
Set<User> followers;

在User实体中匹配Relationship实体中followerId的属性

@ManyToOne
@JoinColumn(name = "user_id")
User followerId;

我错过了什么?

【问题讨论】:

    标签: spring spring-boot spring-data-jpa


    【解决方案1】:

    通过更改修复

    @OneToMany(mappedBy = "followerId")
    Set<User> followers;
    
    @OneToMany(mappedBy = "followedId")
    Set<User> follows;
    

    @OneToMany(mappedBy = "followerId")
    Set<Relationship> followers;
    
    @OneToMany(mappedBy = "followedId")
    Set<Relationship> follows;
    

    在用户实体中,因为一对多关系以关系实体为目标

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多