Hibernate, session, lazyloading

爷,独闯天下 提交于 2019-12-05 19:15:24
ManuPK

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.

I think your first question's answer is you don't commit your session in every usage. I mean in getAllEmployee and getEmployeeByEmployeeId methods you don't commit your transaction. You can add session.getTransaction.commit(); I'm not sure but your first problem may cause the second one because transaction doesn't commit. For the good strategy with session you can look this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!