Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7908575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T12:00:45+00:00 2026-06-03T12:00:45+00:00

I am developing a Java web application using Hibernate and JSF/primefaces. am sometimes getting

  • 0

I am developing a Java web application using Hibernate and JSF/primefaces.
am sometimes getting errors like

1) an object with same identifier is already associated with session.

2) failed to load lazy initialization *,no session exist or session is already closed.

I know this is due to improper coding in my app.
this is the way am doing aap:

When a user requests for a page(Let it be a list of Employees).
the user will get the employee list page(empployeeList.xhtml)
EmployeeListMBean is the managed bean for this page.
in the managed bean in the constructor, am calling a method populateEmployees().
populateEmployee() will use the EmployeeDao method getAllEmployee() to getAllemployees.

Employee Class goes here:

@Entity
@Table(name = "Employee")
@NamedQueries({
    @NamedQuery(name = "Employee.getAllEmployee", query = "from Employee"),
    @NamedQuery(name = "Employee.findEmployeeByFirstName", query = "from Employee where firstName = :firstName"),
    @NamedQuery(name = "Employee.findEmployeeByLastName", query = "from Employee where lastName = :lastName"),
    @NamedQuery(name = "Employee.findEmployeeByMiddleName", query = "from Employee where middleName = :middleName"),
    @NamedQuery(name = "Employee.findEmployeeByOffice", query = "from Employee where office.id = :officeId")
})
public class Employee implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "EID")
    private long id;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
    @Column(name = "GENDER")
    private String gender;
    @Column(name = "DOB")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date dateOfBirth;
    @Column(name = "DOH")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date dateOfHire;
    @ManyToOne(cascade= CascadeType.ALL)
    private Office office;
    @OneToOne(cascade = CascadeType.ALL)
    private ResidenceAddress residence;
    @OneToMany
    private List<Project> projects;

    //getters and setters

}

here is my EmployeeDao:

public class EmployeeDao implements Serializable{
    private SessionFactory factory;
    private Session session;
    public void addEmployee(Employee employee){
        factory = HibernateUtil.getSessionFactory();
        session = factory.openSession();
        session.beginTransaction();
        session.save(employee); 
        session.getTransaction.commit();        
    }
    public List<Employee> getAllEmployee(){
        factory = HibernateUtil.getSessionFactory();
        session = factory.openSession();
        session.beginTransaction();
        List<Employee> cities = session.getNamedQuery("Employee.getAllEmployee").list();
        session.close();
        return cities;
    }

    public Employee getEmployeeByEmployeeId(long employeeId){
        factory = HibernateUtil.getSessionFactory();
        session = factory.openSession();
        session.beginTransaction();
        Employee employee = (Employee) session.get(Employee.class, employeeId);
        session.close();
        return employee;
    }    
}

Question 1)
here, in the methods I am closing the session and then return back the result to managedbeans.
so in the employee listing page the table list out name dob dateOfHire. and I have a buutton view more detail. on clicking this button, I want to display all projects of selected employee working on using the same managedbeans but, it is giving me error(2), failed to lazyload, no session or session already closed.
if I keep the session opened in the getemployeeMethod of dao, I guess that may lead to a memory leak problem, or someother problem. is it so?
also, I have tried lazy and eager loading. please give me a clear idea when/how to use these type of fetching.
How can I solve this? can I go for filters or facelisteners for solving this?

Question 2)
if am trying to edit a project of an employee, and update using session.saveorupadte(), merge(),flush(), am getting an error like this, “an object with same identifier is already associated with session”
How can I solve this?

Question 3)
I know that sessionfactory is resource consuming. so only single instance is enough for one app. but what about session?
for a SINGLE USER of app, only one session is needed?
please tell me good strategy for developing such an app.

Thanking you all 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T12:00:46+00:00Added an answer on June 3, 2026 at 12:00 pm

    As told in the other answer, you should be commiting the transactions you have started. The Transactions are not needed while you are reading the data.

    Question 1 : Lazy Loading.

    You need to lazy load projects, so that it can be used freely in your view. To do that, modify the code as below,

    @OneToMany(fetch=FetchType.LAZY)
    private List<Project> projects;
    

    Question 2 : an object with same identifier is already exist.

    Debug and find out what is the id of the object you are going to save. I can’t much help here without a stacktrace of your error.

    Question 3 : session and sessionfactory.

    Here is the difference between the two from this article.

    SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

    Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

    So, in your code you should create a local variable for session and close it every time you close the method.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am developing a Java Web Application using JSF, Spring and Hibernate. I need
I am developing a java web application using hibernate as ORM. Is it possible
I am developing a Java Web Application using JSF 2.0. Users can upload files.
We are developing a web application using php/java servlets. i would like to pass
I'm developing a web application using Java EE6 and JSF 2.0. I have a
I'm developing an web application in Java and using facebook account for login to
I am developing a Java EE web application using Struts. The problem is with
I am developing a web application using JSF on Netbeans 7.0. I have created
I'm developing java enterprise web application using EJB 3.1 and I wonder which technology
I am developing a web application on JAVA EE 6 with SEAM 3, using

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.