Reputation: 19559
the dao layer of my application need a hibernate reference.
so all the dao bean need it.
I config each, I wander if there are a way to inject a bean to a set of bean in spring? like pointcut expression.
Upvotes: 0
Views: 79
Reputation: 11353
For the Hibernate-specific part of your question, see "Don't repeat the DAO!". The design is as valid today as it was 8 years ago. The gist of it is to not repeat your DAO logic. Instead, create a generic DAO parent class containing repeated CRUD and session management logic. It will typically need two type parameters, one for the type of entity it manages, and another for the type of the entity's @Id
.
Here's a paste from the article. This is the interface
public interface GenericDao <T, PK extends Serializable> {
/** Persist the newInstance object into database */
PK create(T newInstance);
/** Retrieve an object that was previously persisted to the database using
* the indicated id as primary key
*/
T read(PK id);
/** Save changes made to a persistent object. */
void update(T transientObject);
/** Remove an object from persistent storage in the database */
void delete(T persistentObject);
}
and this is the parent class
public class GenericDaoHibernateImpl <T, PK extends Serializable>
implements GenericDao<T, PK>, FinderExecutor {
private Class<T> type;
public GenericDaoHibernateImpl(Class<T> type) {
this.type = type;
}
public PK create(T o) {
return (PK) getSession().save(o);
}
public T read(PK id) {
return (T) getSession().get(type, id);
}
public void update(T o) {
getSession().update(o);
}
public void delete(T o) {
getSession().delete(o);
}
// Not showing implementations of getSession() and setSessionFactory()
}
Or better yet, just use Spring Data JPA.
Upvotes: 1
Reputation: 492
For this you can use autowiring of the bean (Hibernate reference) into your dao layer. You can use autowiring byName so that one name works with all. This is the soul purpose of introducing autowiring so that you do not have to inject them again and again in each bean.
Upvotes: 1