【发布时间】:2014-05-07 06:36:36
【问题描述】:
有两个实体:用户和员工。用户拥有 Employee 类型的字段。
@Entity
@Table(name="user")
public class User extends AuditableEntity {
Long idUser;
String username;
String password;
Employee employee;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getIdUser() { return idUser; }
public void setIdUser(Long idUser) { this.idUser = idUser; }
@Column(name = "username")
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
@Column(name = "password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
@ManyToOne
@JoinColumn(name = "idemployee")
public Employee getEmployee() { return employee; }
public void setEmployee(Employee employee) { this.employee = employee; }
}
还有
@Entity
@Table(name = "employee")
public class Employee extends AuditableEntity {
Long idEmployee;
String surname;
String name;
String patronymic;
Date birthdate;
@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column(name = "idemployee")
public Long getIdEmployee() { return idEmployee; }
public void setIdEmployee(Long idEmployee) { this.idEmployee = idEmployee; }
@Column(name = "surname")
public String getSurname() { return surname; }
public void setSurname(String surname) { this.surname = surname; }
@Column(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Column(name = "patronymic")
public String getPatronymic() { return patronymic; }
public void setPatronymic(String patronymic) { this.patronymic = patronymic; }
@JsonFormat(pattern = "dd.MM.yyyy")
@Column(name = "birthday")
public Date getBirthdate() { return birthdate; }
public void setBirthdate(Date birthdate) { this.birthdate = birthdate; }
}
我需要将用户序列化为 XML/JSON。我正在使用 JAXB,但它也在序列化 Employee:
<User>
<idUser>15</idUser>
<username>user15</username>
<password>password15</password>
<employee>
<idEmployee>23</idEmployee>
<surname>Smith</surname>
<name>John</name>
<patronymic>H.</patronymic>
<birthdate>01.01.1970</birthdate>
</employee>
<User>
我需要这样的结果:
<User>
<idUser>15</idUser>
<username>user15</username>
<password>password15</password>
<idEmployee>23</idEmployee>
<User>
我尝试使用@XmlID、@XmlIDREF - 但它仅适用于 String id 列。 还尝试使用 @XmlTransient - 但它只排除 Employee。 我如何在没有 Employee 的情况下仅使用 idEmployee 来序列化用户?
第二个问题是反序列化。是否有任何标准方法可以做到这一点?
【问题讨论】:
标签: java jpa serialization jaxb