【发布时间】:2011-03-14 18:52:38
【问题描述】:
我们使用 JPA 1.0 和 JAX-WS 完成了最简单的 CRUD 任务。
假设我们有一个实体 Person。
@Entity
public class Person
{
@Id
private String email;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(insertable = false, updatable = false)
private ReadOnly readOnly;
@Column
private String name;
@XmlElement
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
@XmlElement
public Long getReadOnlyValue()
{
return readOnly.getValue();
}
// more get and set methods
}
这是场景。 客户端发出 Web 服务请求以创建人员。在服务器端,一切都很简单。 它确实按预期工作。
@Stateless
@WebService
public class PersonService
{
@PersistenceContext(name = "unit-name")
private EntityManager entityManager;
public Person create(Person person)
{
entityManager.persist(person);
return person;
}
}
现在客户端尝试更新人员,这就是我的 JPA 显示不一致的地方。
public Person update(Person person)
{
Person existingPerson = entityManager.find(Person.class, person.getEmail());
// some logic with existingPerson
// ...
// At this point existingPerson.readOnly is not null and it can't be null
// due to the database.
// The field is not updatable.
// Person object has readOnly field equal to null as it was not passed
// via SOAP request.
// And now we do merge.
entityManager.merge(person);
// At this point existingPerson.getReadOnlyValue()
// will throw NullPointerException.
// And it throws during marshalling.
// It is because now existingPerson.readOnly == person.readOnly and thus null.
// But it won't affect database anyhow because of (updatable = false)
return existingPerson;
}
为了避免这个问题,我需要为 readOnly 对象公开集合并在合并之前执行类似的操作。
Person existingPerson = entityManager.find(Person.class, person.getEmail());
person.setReadOnlyObject(existingPerson.getReadOnlyObject()); // Arghhh!
我的问题:
- 它是一个功能还是只是 不一致?
- 你怎么(或会 你)处理这种情况?请 不要建议我使用 DTO。
【问题讨论】:
-
您有没有找到更好的替代方法来轻松使用不可更新的字段?
标签: jpa jakarta-ee jax-ws