0

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

}
rogerio_gentil
  • 319
  • 1
  • 3
  • 15

1 Answers1

0

You have the first part of the solution by instanciating the personDetail when it's null ,the second part is to check before inserting in database

if the personDetail.getAttributes != null then insert it else insert null

M.A.Bell
  • 326
  • 1
  • 13
  • The problem is that the following exception is throwed even before the view is rendered: `TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing` – rogerio_gentil Apr 02 '18 at 14:06