我正在使用Hibernate和PostgreSQL数据库。 我有几个模式(每个模式都有很多表),还有一个通用方法,该方法接受一个实体类并根据传递的实体返回所有条目:
public <T> List<T> getAll(Class<T> entityClass)
找到实体的表名(例如“ EMPLOYEE”)后,它执行List list = criteria.list();
,创建此SQL SELECT * FROM EMPLOYEE
。但是它会抛出PSQLException: ERROR: relation doesn't exist
,因为它必须为SELECT * FROM MYSCHEMA.EMPLOYEE
(必须附加模式)。怎么处理呢?
这不是我的方法,因为我在持久层中使用Spring Data JPA,它在标识模式方面没有问题,并且在本机休眠中也不好。我正在努力帮助我的同事。
这是方法:
@Override
@Transactional
public <T> List<T> getAll(Class<T> entityClass, Map<String, Object> filter, String... fetchProfiles) {
Session session;
try {
session = sessionFactory.getCurrentSession();
if (fetchProfiles != null) {
for (String fetchProfile : fetchProfiles) {
session.enableFetchProfile(fetchProfile);
}
}
Criteria criteria = session.createCriteria(entityClass);
if (filter != null) {
for (Map.Entry<String, Object> entry : filter.entrySet()) {
if (entry.getValue() == null) {
criteria.add(Restrictions.isNull(entry.getKey()));
} else {
if (entry.getValue() instanceof Collection) {
criteria.add(Restrictions.in(entry.getKey(), (Collection) entry.getValue()));
} else if (entry.getValue() instanceof BetweenValue) {
BetweenValue bv = (BetweenValue) entry.getValue();
if (bv.getBoundLeft() != null) {
criteria.add(Restrictions.ge(entry.getKey(), bv.getBoundLeft()));
}
if (bv.getBoundRight() != null) {
criteria.add(Restrictions.le(entry.getKey(), bv.getBoundRight()));
}
} else if (BaseEntity.class.isAssignableFrom(ReflectionUtils.findField(entityClass, entry.getKey()).getType()) && entry.getValue() instanceof Long) {
BaseEntity fieldEntity = null;
try {
fieldEntity = (BaseEntity) ReflectUtils.createFieldInstance(entityClass, entry.getKey());
} catch (Exception e) {
e.printStackTrace();
}
fieldEntity.setId((Long) entry.getValue());
criteria.add(Restrictions.eq(entry.getKey(), fieldEntity));
} else {
criteria.add(Restrictions.eq(entry.getKey(), entry.getValue()));
}
}
}
}
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List list = criteria.list();
if (fetchProfiles != null) {
for (String fetchProfile : fetchProfiles) {
session.disableFetchProfile(fetchProfile);
}
}
return list;
}