我有兩個具有相同字段的類。但是,其中一個用於JSON ,另一個用於JPA實體。我想將JSON 對象(學生)轉換爲JPA實體(StudentEntity)。我嘗試將JSON類 解析到JPA類中,但它不允許。如何將(Student)Json類轉換爲(StudentEntity)類,以便我可以使用JSON類中的信息從JPA Entity Class中持久化數據庫?Java:將Jackson(JSON)類轉換成實體(JPA)類
package com.student.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Student")
public class StudentEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable = false, updatable = false)
@GeneratedValue
private long studentID;
private String fName;
private String lName;
private Address address;
public long getStudentID() {
return studentID;
}
public void setStudentID(long studentID) {
this.studentID = studentID;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package com.ejb.objectmapper.entity.student;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties("studentID")
public class Student {
private long studentID;
@JsonProperty
private String fName;
@JsonProperty
private String lName;
private Address address;
public long getStudentID() {
return studentID;
}
public void setStudentID(long studentID) {
this.studentID = studentID;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
爲什麼不創建一個轉換器方法並使用getters和setter來使用JSON類中的值創建一個新的實體? 顯然,你不能只將學生投給StudentEntity,因爲他們沒有任何關聯。 – Arqan
轉換器方法是一個簡單而優雅的解決方案,每個人讀你的代碼都會知道它的用途。我想你可以使用反射來設置字段,因爲它們是相同的類型,但爲這樣一個簡單的任務做這件事的想法對我來說聽起來很荒謬。 – Arqan