Reputation: 27
I am new to JPA and multi-tiered architecture way of coding. I am currently working on a new project were we are making an API in which DAO layer is used to communicate with database using JPQL.
Currently, I have written JPQL statements to get data from database. In addition to that,I am also performing lazy initializations to retrieve the complex objects. I want to know if it is right way to perform lazy initializations in DAO layer.
I have 2 more layers before DAO layer called Engine layer and EJB layer where I have the database connection active and can perform lazy initialization there as well. I want to know if it is a good architectural way to do like that because I want the database related to stuff to go only in DAO layer.
But again, I get stuck at a point where I argue myself saying why isn't doing lazy initialization in EJB/Engine layer a good way as I have the database connection active to perform DB operations. I am thinking of this way because I can only retrieve the necessary data in DAO layer which can be reused and lazy initialization can be performed as required by different classes.
I am not sure why I have the DB connection active in Engine and EJB layer( I hope this is for transaction management). It found it is done as per the architect suggestions where I have the EJBs defined as stateless and I have the Engine level classes having databases connections in their scope.
Sorry for lengthy question. Hope I have given necessary details to answer the question.
P.S. Please suggest me any good book or articles which will help me deciding which layer has responsibility of performing what task ideally.
Upvotes: 1
Views: 462
Reputation: 1844
I would say doing it in DAO is the right thing to do. But create a separate method for common use. For example if you have a method to get departments, like
public List<Department> getDepartments() {
//get departments
//Also fetch employees in each department here // DON'T DO
}
It will be nice to have another method specific to fetch all entities and java doc it correctly.
public List<Department> getDepartmentsWithEmployees() {
//get departments
//Also fetch employees in each department here
}
So people will call right method for the need and will reduce the chance of any performance issue.
Note: Use Join Fetch if possible.
Upvotes: 1