2017-12-27 1385 views
0

目前我正在試圖做到這一點:是否可以在不影響第一個對象的情況下將@Entity對象轉換爲普通對象?

我有我的模型

@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 

怎麼可能投學生到學生是一個實體的平原學生?我不知道如何讓它們都實現相同的接口,我不知道是否可能。有任何想法嗎?

我有我的studentRepository基本上我需要返回的學生名單以後將它們轉換成PlainStudent(不知道有沒有更新我的資料庫返回PlainStudent爲好)

我應該放在哪裏註釋?

+0

'@ Entity'只是JPA使用的元數據。它並不是真的需要類類型轉換或繼承。你想解決什麼問題? –

+0

那麼'學生'將不得不延長'PlainStudent'作爲首發 – Antoniossss

+0

我編輯了我的文章,請看看 – jpganz18

回答

1

我不明白你爲什麼會需要它,因爲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."。所以如果學生要延伸PlainStudent,你可以使用演員。但是在學生中你必須註解吸氣劑,因爲變量會被繼承。

相關問題