Search code examples
javajsfpersistenceentities

updating different jpa entities from a single html form (jsf page)


I have been reviewing some samples posted online and they all do the simple CRUD.

1 jsf page = 1 entity = 1 table.

most of the time, this is what I see. but what if you only have 1 jsf page with 1 form, and you need to supply data to 3 entities. having form fields such as name, company and hobby.

their values need to be put to entities

person.name, work.company_name and other_info.hobby.

is this done automatically by binding? or we need to do some manual assigning of values? please shed some light, i am a kind of confused right now


Solution

  • I'm not sure if I see the problem. You could just make them properties of the same backing bean:

    @ManagedBean
    @ViewScoped
    public class Profile {
    
        private Person person;
        private Work work;
        private OtherInfo otherInfo;
    
        // ...
    }
    

    with

    <h:inputText value="#{profile.person.name}" />
    <h:inputText value="#{profile.work.companyName}" />
    <h:inputText value="#{profile.otherInfo.hobby}" />
    

    Or if Work and OtherInfo have an @OneToOne relationship with Person (in real world, they undoubtedly have):

    @ManagedBean
    @ViewScoped
    public class Profile {
    
        private Person person; // Has in turn Work and OtherInfo properties.
    
        // ...
    }
    

    with

    <h:inputText value="#{profile.person.name}" />
    <h:inputText value="#{profile.person.work.companyName}" />
    <h:inputText value="#{profile.person.otherInfo.hobby}" />