有两个实体:用户和员工。用户具有类型为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; }
}
我需要将User序列化为XML / JSON。我使用的是JAXB,但它也在对员工进行序列化:
<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。 如何在没有员工的情况下序列化用户,仅使用idEmployee?
第二个问题是反序列化。有没有标准的方法可以做到这一点?
答案 0 :(得分:0)
使用employee
在课程User
中注释属性@XmlTransient
。此注释可应用于字段或其getter。
答案 1 :(得分:0)
您可以将员工ID的其他getter添加到User
实体
public class User
{
...
@Transient // for JPA
@XmlElement
Long getIdEmployee()
{
return employee.getIdEmployee();
}
}
或者您可以使用@XmlValue
public class User
{
...
@XmlElement(name = "idEmployee")
public Employee getEmployee() { return employee; }
public void setEmployee(Employee employee) { this.employee = employee; }
}
@XmlAccessorType(XmlAccessType.NONE) // to prevent marshalling of all properies
public class Employee
{
...
@XmlValue
public Long getIdEmployee() { return idEmployee; }
...
}