gpt4 book ai didi

Hibernate、 session 、延迟加载

转载 作者:行者123 更新时间:2023-12-02 23:37:40 25 4
gpt4 key购买 nike

我正在使用 Hibernate 和 JSF/primefaces 开发 Java Web 应用程序。有时会遇到类似的错误

1) 具有相同标识符的对象已与 session 关联。

2) 加载延迟初始化失败*,不存在 session 或 session 已关闭。

我知道这是由于我的应用程序中的编码不当造成的。这就是我做 aap 的方式:

当用户请求页面时(让它成为员工列表)。用户将获得员工列表页面(employeeList.xhtml)EmployeeListMBean 是此页面的托管 bean。在构造函数的托管 bean 中,我调用了 populateEmployees() 方法。populateEmployee() 将使用 EmployeeDao 方法 getAllEmployee() 来获取Allemployees。

员工类别位于此处:

@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

}

这是我的 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;
}
}

问题1)在这里,在方法中我关闭 session ,然后将结果返回给托管bean。因此,在员工列表页面中,表格列出了姓名 dob dateOfHire。我有一个按钮查看更多细节。单击此按钮时,我想显示所选员工使用相同托管bean 进行工作的所有项目,但是,它给了我错误(2)、延迟加载失败、没有 session 或 session 已关闭。如果我在 dao 的 gettemployeeMethod 中保持 session 打开,我想这可能会导致内存泄漏问题或其他问题。是这样吗?另外,我尝试过延迟加载和急切加载。请给我一个清晰的想法何时/如何使用这些类型的获取。我该如何解决这个问题?我可以使用过滤器或面部监听器来解决这个问题吗?

问题2)如果我尝试编辑员工的项目,并使用 session.saveorupadte()、merge()、flush() 进行更新,则会收到如下错误:“具有相同标识符的对象已与 session 关联”我该如何解决这个问题?

问题3)我知道sessionfactory很消耗资源。因此对于一个应用程序来说,只有一个实例就足够了。但是 session 呢?对于应用程序的单个用户,只需要一个 session ?请告诉我开发此类应用程序的好策略。

谢谢大家:)

最佳答案

正如另一个答案中所述,您应该提交您已开始的事务。当您读取数据时不需要事务。

Question 1 : Lazy Loading.

您需要lazy load projects,这样就可以在你的 View 中自由使用了。为此,请修改以下代码,

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

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

调试并找出您要保存的对象的id。如果没有错误的堆栈跟踪,我在这里无法提供太多帮助。

Question 3 : session and sessionfactory.

这是两者之间的区别 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.

因此,在您的代码中,您应该为 session 创建一个局部变量,并在每次关闭方法时关闭它。

关于Hibernate、 session 、延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10023444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com