gpt4 book ai didi

java - Spring 数据。存储库返回错误的Id(实体数据正确)

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

美好的一天,这里有问题:CrudRepository 返回错误的实体 ID。

这是基本 JPA 用户实体:

@Data
@Entity(name = "user")
@EqualsAndHashCode(exclude = {"roles", "password", "data"})
@ToString(exclude = {"roles", "password", "data"})
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne(mappedBy = "user", fetch = FetchType.LAZY)
private SomeData data;
...

与某些数据实体存在一对一的关系。

@Data
@Entity(name = "some_data")
@TypeDefs({
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
@ToString(exclude = {"user", "views", "biData"})
@EqualsAndHashCode(exclude = {"user", "views", "biData"})
public class SomeData {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToOne
@MapsId
private User user;
...

并且有 CRUD 存储库:

@Repository
public interface SomeDataRepository extends CrudRepository<SomeData, Long> {

Optional<SomeData> findByUserId(Long userId);
}

方法 findUserById 从数据库返回正确的 SomeData 实体,但该实体与 userId 具有相同的 ID...因此,我无法执行其他 Activity (在表“public_view”上插入或更新违反了外键约束“fk_view_to_some_data”)

这很奇怪。

最佳答案

问题可能是因为您使用了 @MapsId 注释。以下是注释值的作用,如 Javadoc :

The name of the attribute within the composite key to which the relationship attribute corresponds. If not supplied, the relationship maps the entity's primary key.

您可以尝试为注释设置特定值,或者以不同的方式映射您的一对一关系。例如,在 SomeData 类中使用 @JoinColumn 注释:

// ... your annotations ...
public class SomeData {

// ... your other fields ...

@OneToOne
@JoinColumn(name = "some_data_id", referencedColumnName = "id")
private User user;

}

以下是您可以使用的一些替代方案:https://www.baeldung.com/jpa-one-to-one

关于java - Spring 数据。存储库返回错误的Id(实体数据正确),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503839/

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