jpa Hibernate:JSON中只有id的实体关系?

gr8qqesn  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(188)

我有两个实体:用户和设备.每个设备应该有一个用户.但用户已经存在,所以我想通过ID链接到我的设备的用户.目前,我必须创建一个用户,并将其作为后请求发送到我的后端.但我只想发送应该存储的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"
}

我试过通过关系(多对一和一对多),但它没有工作。

cngwdvgl

cngwdvgl1#

你可以做的一件事就是继续发送ownerId -就像你的例子一样。之后,你可以像往常一样Map其他字段,当涉及到所有者时,使用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

相关问题