In a JSF form there is:
<h:inputText value="#{personBean.person.personDetail.attribute}" />
The entity Person
is loaded from database on PostConstruct
annotated method. However, the attribute personDetail
of Person
instance can be null. Thereby, when the input is filled and form is submitted, an exception is throwed (more specifically javax.el.PropertyNotFoundException: (...) Target Unreachable, ''personDetail'' returned null
).
I searched and found some excellent examples to solve this exception, such as:
But, I think that issue is different. The person
instance is found and its instance attribute can be null.
I've also tried to set a new instance of PersonDetail
when it is null on PostConstruct
method, but thereof the issue becomes a persistence problem because the "object (personDetail
) references an unsaved transient instance".
So, how to treat this issue?
Source
Short backing bean :
@Named(value = "personBean")
@ViewScoped
public class PersonBean {
(...)
@PostConstruct
public void init() {
person = personService.findById(1L);
// throw -> TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing
// if (person.getPersonDetail() == null) {
// person.setPersonDetail(new PersonDetail());
// }
(...)
}
}
Short entity classes:
@Entity
public class Person {
(...)
@OneToOne(mappedBy = "pessoa", fetch = FetchType.LAZY)
private PersonDetail personDetail;
// Getters and Setters
}
-
public class PersonDetail {
private String attribute;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_id", unique = true, nullable = false)
private Person person;
// Getters and Setters
}