gpt4 book ai didi

java - 乘以 ID 映射抛出 BaseEntity

转载 作者:行者123 更新时间:2023-12-02 01:08:05 25 4
gpt4 key购买 nike

我正在通过 Hibernate 映射类,并且需要为 Relationship 映射多个 ID。所有 ID 均从 BaseEntity 扩展。如何为 Relationship 实现多个 ID 映射,其中包含数据库中 User 的外键?

基本上,Relationship 中的字段 userIdOneuserIdTwo 必须包含发送请求的用户 ID。

UserBaseEntity扩展自己的ID。

每次运行它时 - 都会出现错误:

This class [class com.mylov.springsocialnetwork.model.Relationship] does not define an 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;
}

最佳答案

您似乎希望在两个不同的用户之间建立关系。这意味着每个 Relationship 都是它自己的对象/实体,并且应该有自己的 @Id (与用户 ID 无关)。构成此关系的每个User的链接应映射为外键(可能是@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 映射将没有它也可以正常工作,因为它从您定义的模型中获取关系,而不是从数据库本身。

关于java - 乘以 ID 映射抛出 BaseEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57712409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com