我建議使用UNION,但如果我沒有弄錯,HQL不支持UNION,所以你必須使用原生查詢和結果轉換器。這裏有一個例子:
public class Log {
private Long id;
private Long memberId;
private String logType;
private Date dateChanged;
// getters & setters here
}
public class LogService {
@PersistenceContext
private EntityManager em;
public List<Log> getLogs(){
final Session sess = em.unwrap(Session.class);
final SQLQuery query = session.createSQLQuery(
"select id,memberId,'CONTACT' as logType, dateChanged from contactLog"+
"union select id,memberId,'SALARY' as logType,dateChanged from salaryLog"+
"union select id,memberId,'RELATIONS' as logType,dateChanged from relationsLog"+
"union select id,memberId,'PERSONAL INFO' as logType,dateChanged from personalInfoLog "+
"order by dateChanged desc";
);
query.setResultTransformer(Transformers.aliasToBean(Log.class));
return query.list();
}
}
注意,只有共同的列選擇(因爲你必須從每個表使用UNION時選擇相同的列數)。
如果您想查看日誌的完整詳細信息,只需使用id加載特定日誌和日誌類型即可知道從哪個表中查找完整信息。
或
你可以修改查詢到Concat的所有更改的信息合併到一列的所有表(這意味着Log.class添加一個新的領域)。
public class Log {
private Long id;
private Long memberId;
private String logType;
private Date dateChanged;
private String changedInfo;
// getters & setters here
}
"select id,memberId,'CONTACT' as logType, dateChanged, phonenumber||','||email||','||address as changedInfo from contactLog"+
"union select id,memberId,'SALARY' as logType,dateChanged,salary as changedInfo from salaryLog"+
"union select id,memberId,'RELATIONS' as logType,dateChanged,relationId as changedInfo from relationsLog"+
"union select id,memberId,'PERSONAL INFO' as logType,dateChanged, height||','|| weight||','|| eyeColor||','|| hairColor as changedInfo from personalInfoLog "+
"order by dateChanged desc
比回答更多評論... – hd1