Hibernate:在JSON中只与id的实体关系?



我有两个实体:用户和设备。每个设备应该有一个用户。但是用户已经存在,所以我想通过Id链接用户到我的设备。此刻,我必须创建一个用户,并将其作为Post-Request发送到我的后端。但是我只想发送应该被存储的Id。

我已经创建了一个应用程序,必须通过json文件传输数据

@Entity
@Table(name = "Users")
public class User {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
private boolean activity;
private boolean login;
Entity
@Table(name = "Devices")
public class Device {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id
private boolean activity;
private String location;
@OneToOne
@JoinColumn(name = "UserId", referencedColumnName = "id")
private User owner;
//This is the JSON-File how I have to send it
{
"activity": "true",
"location": "Room 102",
"owner": {
"name": "Mike",
"email": "testMail@test.com",
"password": "123456",
"activity": "true",
"login": "false"
}
}
//This is how I would like to send it (Only sending the Id of the other Table)
{
"activity": "true",
"location": "Room 102",
"owner": "1"
}

我试过通过关系(ManyToOne &OneToMany),但没有成功。

您可以做的一件事是继续发送ownerId -就像您的示例一样。之后,您可以像往常一样映射其他字段,并且,当涉及到所有者时,使用entityManagerJpaRepository并调用getReference方法。

这将返回看起来像User的东西,它可以用于其他查询或数据库操作,但它实际上只是一个基于给定id的代理:

User owner = entityManager.getReference(User.class, deviceDto.getOwner());
Device device = mapper.map(deviceDto); // map the other fields
device.setOwner(owner);
deviceRepository.save(device);

在这里阅读更多信息:https://www.baeldung.com/jpa-entity-manager-get-reference

最新更新