我正在通过Hibernate映射类,我需要为Relationship映射多个ID。所有ID都是从BaseEntity扩展来的。如何为Relationship实现多个ID映射,其中包含User在DataBase中的外键?
基本字段userIdOne和userIdTwo在Relationship中必须包含用户发送请求的id。
User从BaseEntity扩展自己的ID。
每次我运行它时-获取错误:
这个类com.mylov.springsocialnetwork.model.Relationship不定义IdClass
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@MappedSuperclass
@EqualsAndHashCode
public class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
}
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(exclude = {"posts"}, callSuper = false)
@Entity
public class User extends BaseEntity {
private String userName;
private String realName;
private String email;
private String phoneNumber;
private LocalDate birthDate;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "userPosted")
private Set<Post> posts = new HashSet<>();
private String password;
public User(Long id, String userName, String realName, String email, String phoneNumber, LocalDate birthDate,
Set<Post> posts, String password) {
super(id);
this.userName = userName;
this.realName = realName;
this.email = email;
this.phoneNumber = phoneNumber;
this.birthDate = birthDate;
this.posts = posts;
this.password = password;
}
}
@Builder
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Relationship implements Serializable {
//@Id not working
private Long userIdFrom;
//@Id
private Long userIdTo;
@Enumerated(value = EnumType.STRING)
private RelationshipStatus status;
private LocalDate friendsRequestDate;
}发布于 2019-08-29 14:49:32
您似乎希望在两个不同的用户之间建立一个Relationship。这意味着每个Relationship都是自己的对象/实体,并且应该有自己的@Id (与用户ID无关)。应该将构成此User的每个Relationship的链接映射为外键(可能是@ManyToOne和@JoinColumn)。
例如:
@Entity
public class Relationship implements Serializable {
@Id
private Long relationshipId;
@ManyToOne(...)
@ForeignKey(name="FK_USER_ONE") //for generation only, it isn't strictly required
@JoinColumn(name="from")
private Long userIdFrom;
@ManyToOne(...)
@ForeignKey(name="FK_USER_TWO") //for generation only, it isn't strictly required
@JoinColumn(name="to")
private Long userIdTo;
@Enumerated(value = EnumType.STRING)
private RelationshipStatus status;
private LocalDate friendsRequestDate;
}编辑:它不需要指定@ForeignKey注释。如果数据库表是自动生成的(可以用于测试,但通常不是生产中您想要的东西),并且相应地在表上创建FOREIGN KEY约束,那么它们将被使用,但是JPA映射在没有它的情况下会很好地工作,因为它从您定义的模型中获取关系,而不是从数据库本身。
https://stackoverflow.com/questions/57712409
复制相似问题