1

Sorry if my post is duplicate but i can't solution for my problem from another topic so I create this topic. Hope anyone help me. I'm using Hibernate, JSF and Glassfish.

Table Relationship enter image description here

Here is my full code

customerBean (requestscoped)

public class customerBean implements Serializable {

    private CustomerProfile selectedCustomer = new CustomerProfile();
    private List<CustomerProfile> customer;

    /** Creates a new instance of customerBean */
    public customerBean() {
    }

    public List<CustomerProfile> getCustomer() {
        customerDao cust_dao = new customerDao();
        customer = cust_dao.findAll();
        return customer;
    }

    public CustomerProfile getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(CustomerProfile selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    public void btnUpdate(){
        customerDao cust_create = new customerDao();
        String msg;
        if(cust_create.updateCustomer(selectedCustomer)){
            msg = "Updated Successfully!";
        }else{
            msg = "Error. Please check again!";
        }
        FacesMessage massage = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
        FacesContext.getCurrentInstance().addMessage(null, massage);
    }
}

customerDao

public class customerDao {
    public List<CustomerProfile> findAll(){
        List<CustomerProfile> list_cust = null;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        String sql = "FROM CustomerProfile";
        try{
            session.beginTransaction();
            list_cust = session.createQuery(sql).list();
            session.beginTransaction().commit();
        }catch(Exception e){
            session.beginTransaction().rollback();
        }
        return list_cust;
    }

    public boolean updateCustomer(CustomerProfile customer){
        boolean flag;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        try{
            session.beginTransaction();
            CustomerProfile cust_info = (CustomerProfile) session.load(CustomerProfile.class, customer.getProfile());
            cust_info.setFullname(customer.getFullname());
            cust_info.setEmail(customer.getEmail());
            cust_info.setPhone(customer.getPhone());
            session.merge(customer);
            session.beginTransaction().commit();
            flag = true;
        }catch(Exception e){
            flag = false;
            e.printStackTrace();
            session.beginTransaction().rollback();
        }
        return flag;
    }
}

xhtml

<p:growl id="msgs" showDetail="true" />
<h:form id="formData">
<p:dataTable id="customers" var="customer_profile" value="#{customerBean.customer}" paginator="true" paginatorPosition="bottom" rows="10"
             paginatorTemplate="{PreviousPageLink} {PageLinks} {NextPageLink} {RowsPerPageDropdown}"
             rowsPerPageTemplate="5,10,15">

    <p:column headerText="Customer ID">
        <h:outputText value="#{customer_profile.customer.customId}" />
    </p:column>

    <p:column headerText="Full Name">
        <h:outputText value="#{customer_profile.fullname}" />
    </p:column>

    <p:column headerText="Phone">
        <h:outputText value="#{customer_profile.phone}" />
    </p:column>

    <p:column headerText="Email">
        <h:outputText value="#{customer_profile.email}" />
    </p:column>

    <p:column headerText="Order">
        <h:outputText value="#{customer_profile.quantityOrder}" />
    </p:column>

    <p:column headerText="Date Created">
        <h:outputText value="#{customer_profile.dateCreated}" />
    </p:column>

    <p:column>
        <p:commandButton id="btnUpdate" oncomplete="updateDialog.show()" icon="ui-icon-search" title="Update" update=":formUpdate">
            <f:setPropertyActionListener value="#{customer_profile}" target="#{customerBean.selectedCustomer}" />
        </p:commandButton>
    </p:column>

</p:dataTable>
</h:form>

<!-- Start formUpdate -->
<h:form id="formUpdate">
<p:dialog header="Customer Details" widgetVar="updateDialog" resizable="false" id="updateDlg" showEffect="fade" hideEffect="explode">

    <h:panelGrid id="display" columns="2" cellpadding="4" style="margin:0 auto;">

        <h:outputText value="Profile ID: " />
        <h:outputLabel value="#{customerBean.selectedCustomer.profile}" />
        <h:outputLabel value="#{customerBean.selectedCustomer.customer.loginName}" />

        <h:outputText value="Full Name: " />
        <h:inputText value="#{customerBean.selectedCustomer.fullname}" />

        <h:outputText value="Phone: " />
        <h:inputText value="#{customerBean.selectedCustomer.phone}" />

        <h:outputText value="Email: " />
        <h:inputText value="#{customerBean.selectedCustomer.email}" />    

        <f:facet name="footer">
            <p:separator />
            <p:commandButton id="btnOK" immediate="true" oncomplete="updateDialog.hide()" action="#{customerBean.btnUpdate}" icon="ui-icon-search" title="Save" value="Save" update=":formData, :msgs" />
            <p:commandButton id="btnCancel" oncomplete="updateDialog.hide()" icon="ui-icon-search" title="Cancel" value="Cancel" />
        </f:facet>
    </h:panelGrid>

</p:dialog>
</h:form>
<!-- End formUpdate -->

I got this error:

SEVERE: javax.el.ELException: /admin/customer_list.xhtml @68,106 value="#{customerBean.selectedCustomer.customer.loginName}": org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Updated

Customer.hbm.xml

<hibernate-mapping>
  <class catalog="catering" name="entities.Customer" schema="dbo" table="customer">
    <id name="customId" type="int">
      <column name="customID"/>
      <generator class="assigned"/>
    </id>
    <property name="loginName" type="string">
      <column name="loginName" not-null="true" unique="true"/>
    </property>
    <property name="password" type="string">
      <column name="password"/>
    </property>
    <set inverse="true" name="customerProfiles">
      <key>
        <column name="customID"/>
      </key>
      <one-to-many class="entities.CustomerProfile"/>
    </set>
    <set inverse="true" name="orderses">
      <key>
        <column name="customID" not-null="true"/>
      </key>
      <one-to-many class="entities.Orders"/>
    </set>
  </class>
</hibernate-mapping>

Customer.java

public class Customer  implements java.io.Serializable {
     private int customId;
     private Serializable loginName;
     private Serializable password;
     private Set customerProfiles = new HashSet(0);
     private Set orderses = new HashSet(0);

    public Customer() {
    }


    public Customer(int customId, Serializable loginName) {
        this.customId = customId;
        this.loginName = loginName;
    }
    public Customer(int customId, Serializable loginName, Serializable password, Set customerProfiles, Set orderses) {
       this.customId = customId;
       this.loginName = loginName;
       this.password = password;
       this.customerProfiles = customerProfiles;
       this.orderses = orderses;
    }

    public int getCustomId() {
        return this.customId;
    }

    public void setCustomId(int customId) {
        this.customId = customId;
    }
    public Serializable getLoginName() {
        return this.loginName;
    }

    public void setLoginName(Serializable loginName) {
        this.loginName = loginName;
    }
    public Serializable getPassword() {
        return this.password;
    }

    public void setPassword(Serializable password) {
        this.password = password;
    }
    public Set getCustomerProfiles() {
        return this.customerProfiles;
    }

    public void setCustomerProfiles(Set customerProfiles) {
        this.customerProfiles = customerProfiles;
    }
    public Set getOrderses() {
        return this.orderses;
    }

    public void setOrderses(Set orderses) {
        this.orderses = orderses;
    }
}

CustomerProfile.hbm.xml

<hibernate-mapping>
  <class catalog="catering" name="entities.CustomerProfile" schema="dbo" table="customer_profile">
    <id name="profile" type="int">
      <column name="profile"/>
      <generator class="assigned"/>
    </id>
    <many-to-one class="entities.Customer" fetch="select" name="customer">
      <column name="customID"/>
    </many-to-one>
    <property name="gender" type="java.lang.Boolean">
      <column name="gender"/>
    </property>
    <property name="fullname" type="string">
      <column name="fullname" not-null="true"/>
    </property>
    <property name="phone" type="string">
      <column length="15" name="phone" not-null="true"/>
    </property>
    <property name="email" type="string">
      <column name="email"/>
    </property>
    <property name="quantityOrder" type="java.lang.Integer">
      <column name="quantityOrder"/>
    </property>
    <property name="isVegetarian" type="java.lang.Boolean">
      <column name="isVegetarian"/>
    </property>
    <property name="dateCreated" type="date">
      <column name="dateCreated"/>
    </property>
  </class>
</hibernate-mapping>

CustomerProfile.java

public class CustomerProfile  implements java.io.Serializable {
     private int profile;
     private Customer customer;
     private Boolean gender;
     private Serializable fullname;
     private String phone;
     private Serializable email;
     private Integer quantityOrder;
     private Boolean isVegetarian;
     private Serializable dateCreated;

    public CustomerProfile() {
    }


    public CustomerProfile(int profile, Serializable fullname, String phone) {
        this.profile = profile;
        this.fullname = fullname;
        this.phone = phone;
    }
    public CustomerProfile(int profile, Customer customer, Boolean gender, Serializable fullname, String phone, Serializable email, Integer quantityOrder, Boolean isVegetarian, Serializable dateCreated) {
       this.profile = profile;
       this.customer = customer;
       this.gender = gender;
       this.fullname = fullname;
       this.phone = phone;
       this.email = email;
       this.quantityOrder = quantityOrder;
       this.isVegetarian = isVegetarian;
       this.dateCreated = dateCreated;
    }

    public int getProfile() {
        return this.profile;
    }

    public void setProfile(int profile) {
        this.profile = profile;
    }
    public Customer getCustomer() {
        return this.customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public Boolean getGender() {
        return this.gender;
    }

    public void setGender(Boolean gender) {
        this.gender = gender;
    }
    public Serializable getFullname() {
        return this.fullname;
    }

    public void setFullname(Serializable fullname) {
        this.fullname = fullname;
    }
    public String getPhone() {
        return this.phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Serializable getEmail() {
        return this.email;
    }

    public void setEmail(Serializable email) {
        this.email = email;
    }
    public Integer getQuantityOrder() {
        return this.quantityOrder;
    }

    public void setQuantityOrder(Integer quantityOrder) {
        this.quantityOrder = quantityOrder;
    }
    public Boolean getIsVegetarian() {
        return this.isVegetarian;
    }

    public void setIsVegetarian(Boolean isVegetarian) {
        this.isVegetarian = isVegetarian;
    }
    public Serializable getDateCreated() {
        return this.dateCreated;
    }

    public void setDateCreated(Serializable dateCreated) {
        this.dateCreated = dateCreated;
    }
}
Hung PD
  • 395
  • 2
  • 13
  • 32

2 Answers2

2

Hibernate uses proxy objects when you have relationships to other entities, this proxy helps to get the info from the DataBase only when it is needed so it mechanism is called a lazy initialization, and to get the info it needs the session object, the object customer in your list is not initialize so you need to do it, explicit so:

public List<CustomerProfile> findAll(){
        List<CustomerProfile> list_cust = null;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        String sql = "FROM CustomerProfile";
        try{
            session.beginTransaction();
            list_cust = session.createQuery(sql).list();
            for (CustomerProfile cp : list_cust) {
                Hibernate.initialize(cp.getCustomer());
                //or cp.getCustomer().getLoginName();
            }
            session.beginTransaction().commit();
        }catch(Exception e){
            session.beginTransaction().rollback();
        }
        return list_cust;
    }
Cesar Loachamin
  • 2,680
  • 4
  • 24
  • 33
  • it said "customer has private access in entities.CustomerProfile" – Hung PD Dec 26 '13 at 18:11
  • Could you try with or cp.getCustomer().getLoginName() instead of Hibernate.initialize – Cesar Loachamin Dec 26 '13 at 18:15
  • Thank you now I can get info from Customer table. But i have 2 additional question. 1) Why only need cp.getCustomer().getLoginName(). 2) When I update customer info, i get this error "SEVERE: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [entities.CustomerProfile#0]" – Hung PD Dec 26 '13 at 18:20
  • Ok for the first question, (I update my answer to use Hibernate.initialize) when you call a getter for the proxy object (Customer) only in that moment hibernate will make a select in the database to get the info for that field. So that could answer the second question the customer id field is never initialized I'm not sure how the proxy objects works in hibernate but in the other ORM's as eclipse link or openjpa when you access a field of a proxy all the object is fill, maybe this is no the case for hibernate so try to use the Hibernate.initialize in the way I update my answer. – Cesar Loachamin Dec 26 '13 at 18:30
  • I trying with you updated answer but second problem is still not resolve. – Hung PD Dec 26 '13 at 18:40
  • This error is because the field that is id for the CustomerProfile is 0 and there is no row with this value as pk – Cesar Loachamin Dec 26 '13 at 19:17
  • This code to get Id, hope you help me :( "CustomerProfile cust_info = (CustomerProfile) session.load(CustomerProfile.class, customer.getProfile());" – Hung PD Dec 26 '13 at 19:24
  • customer.getProfile() returns 0, and there is no row with 0 as value for the pk. – Cesar Loachamin Dec 26 '13 at 19:26
  • I'm not sure how your entities are, you don't post the code, but I think you're trying to find a CustomerProfile by its id (That's what the load method does) so first check if the customer.getProfile() returns the Object CustomerProfile you has already get the object, do it in a session context, or if you are trying to find an object given it's primary key you should do this "CustomerProfile cust_info = (CustomerProfile) session.load(CustomerProfile.class, customer.getProfileId());" or "CustomerProfile cust_info = (CustomerProfile) session.load(CustomerProfile.class, new Integer(135));", – Cesar Loachamin Dec 26 '13 at 19:32
  • another option is if you have the value of the primary key make a query to find the object – Cesar Loachamin Dec 26 '13 at 19:34
  • I updated two table code. Hope you help me :) – Hung PD Dec 26 '13 at 19:37
  • Sorry recently I see the code – Cesar Loachamin Dec 26 '13 at 19:45
  • Could you tell me what is exactly you want to do?? Find a CustomerProfile given its id?? – Cesar Loachamin Dec 26 '13 at 19:48
  • Exactly i want to do that update customer info (based on Profileid or Customer id) – Hung PD Dec 26 '13 at 19:52
  • I check the code but I don't find where the error is. But the reason is that customer.getProfile() returns 0, but I don't understand why the selectedCustomer has that 0 – Cesar Loachamin Dec 26 '13 at 20:03
  • To check the value can you show the value of #{customer_profile.profile} in the table as p:column – Cesar Loachamin Dec 26 '13 at 20:07
  • I can show in table, but don't know why it return 0 – Hung PD Dec 27 '13 at 03:35
  • Are you sure that profile column is the pk and in the database table the value isn't 0 – Cesar Loachamin Dec 27 '13 at 03:43
  • yes bro, please check table relationship and my code. – Hung PD Dec 27 '13 at 03:47
  • I have checked, but I don't find the problem. I suggest you to start debugging from the findAll method and check if the profile value is set different to 0 – Cesar Loachamin Dec 27 '13 at 03:56
  • can you teamviewer to help me? – Hung PD Dec 27 '13 at 04:22
  • Sure write me to my email, this is in my profile information – Cesar Loachamin Dec 27 '13 at 15:55
  • 1
    thanks for that Iteration part !!! – Shantaram Tupe Nov 22 '17 at 10:13
0

This is maybe unrelated but I find this pattern problematic.

    try{
        session.beginTransaction();
        // do something
        session.beginTransaction().commit();
    }catch(Exception e){
        session.beginTransaction().rollback();
    }

You should not be calling 3 times beginTransaction.
I mean, I doubt your code does what you wanted it to do.

Check the top of this page to see how this pattern should look like.

http://docs.jboss.org/hibernate/annotations/3.5/api/org/hibernate/Session.html

peter.petrov
  • 34,474
  • 11
  • 63
  • 118
  • @peter-petrov When I update customer info, i get this error "SEVERE: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [entities.CustomerProfile#0]" – Hung PD Dec 26 '13 at 19:09