how to get generic class type in HQL

Recently, I faced up a problem in my project. I tried to use generic type in my project, but when it came to the hibernate hql, I can not get the generic type. Following is the solution:

Let’s begin

Step 1:

Suppose I have a normal class like findById.

1
2
3
4
5
6
7
8
@Override
public User findById(Long id) {
String hql = "FROM User u where u.id = :userId";
Session s = sessionFactory.getCurrentSession();
TypedQuery<User> query = s.createQuery(hql);
query.setParameter("userId", id);
return query.getSingleResult();
}

Step 2:

I write a CRUDDaoImpl to let all the class be generic type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Repository // new CRUDDaoImpl()
@Transactional
//T=B, ID=IB
public abstract class CRUDDaoImpl<B,IB> implements CRUDDao<B,IB>{

@Autowired
private SessionFactory sessionFactory;

@Override
public B findById(IB ib) {
String hql = "FROM "+xxx +" b where b.id = :iibb";
TypedQuery<B> query = sessionFactory.getCurrentSession().createQuery(hql).setParameter("iibb",ib);
return query.getSingleResult();
}


}

Step 3:

Here we are going to get the class type of B to replace the “xxx” in the HQL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Repository // new CRUDDaoImpl()
@Transactional
//T=B, ID=IB
public abstract class CRUDDaoImpl<B,IB> implements CRUDDao<B,IB>{

protected Class<B> hQLEntityClazz;

public abstract void setHQLEntityClazz();

@Autowired
private SessionFactory sessionFactory;

@Override
public B findById(IB ib) {
String hql = "FROM "+hQLEntityClazz.getName() +" b where b.id = :iibb";
TypedQuery<B> query = sessionFactory.getCurrentSession().createQuery(hql).setParameter("iibb",ib);
return query.getSingleResult();
}


}

Here we should implement the setHQLEntityClazz method in the UserDaoImpl:

1
2
3
4
5
6
7
8
9
10
11
public class UserDaoImpl extends CRUDDaoImpl<User,Long> implements UserDao{

@Autowired
private SessionFactory sessionFactory;

@Override
@Autowired
public void setHQLEntityClazz() {
this.hQLEntityClazz = User.class;
}
}

That’s all, thank you!

0%