gpt4 book ai didi

java - 是否可以将 @Entity 对象转换为普通对象而不影响第一个对象?

转载 作者:行者123 更新时间:2023-12-02 11:49:10 25 4
gpt4 key购买 nike

我目前正在尝试这样做:

我有我的模型

@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue(strategy = IDENTITY)
private long id;

@Column(name = "name")
private String name;
...

我还有其他对象,比如说 PlainStudent

public class PlainStudent{

private long id;
private String name;

... other fields

当 Student 是一个实体时,如何将 Student 转换为 PlainStudent?我不知道如何让它们都实现相同的接口(interface),也不知道是否可能。有什么想法吗?

我有我的学生存储库,基本上我需要返回学生列表,以便稍后将它们转换到 PlainStudent (不知道我是否也必须更新我的存储库以返回 PlainStudent)

我应该在哪里放置注释?

最佳答案

我不明白为什么你需要它,因为 JPA 注释在 JPA 之外没有效果,但如果你这样做,你可以编写一个构造函数:

PlainStudent (Student student) { this.id = student.id; this.name = student.name; ...}

然后使用它:

PlainStudent plainStudent = new PlainStudent (student);

顺便说一句,JPA 支持继承:"Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes." 。因此,如果 Student 要扩展 PlainStudent,您可以使用强制转换。但是在 Student 中,您必须注释 getter,因为变量将被继承。

关于java - 是否可以将 @Entity 对象转换为普通对象而不影响第一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998114/

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