我嘗試用Hibernate做一些簡單的inner join查詢,不過下的SQL必須是符合某特定形式
才能正常運作。例如:
public class TestDao extends HibernateDaoSupport {
query = getSession().createSQLQuery("select c1.*,c2.* from Customer c1
inner join Country c2 on c1.country_id=c2.country_id where c1.name=:name");
query.setParameter("name", name);
query.addEntity(Customer.class).addEntity(Country.class);
list = query.list();
return list;
}
但如果把上面SQL的星號改成欄位名稱,就會跳錯,例如改成:
select c1.name,c2.country_name from Customer c1 inner join Country c2 on
c1.country_id=c2.country_id where c1.name=:name
執行到
list = query.list();
就會跳以下的錯誤訊息:
[org.hibernate.exception.GenericJDBCException: could not execute query] with
root cause
java.sql.SQLException: 資料欄名稱無效
這樣就變成每次查詢都要撈出全部資料才可以,顯得很多餘,但是又想不到如何修改
請問為何SQL打星號可以過,打欄位名稱就過不了呢?
那又要如何修改呢?
改寫成以下這樣即可:
query =
hibernateTemplate.getSessionFactory().openSession().createSQLQuery(
"select name,(select country_name from Country c1 inner join Customer c2 on
c1.country_id=c2.country_id where name=:name) country_name from Customer c3");
//將addEntity那行改成以下寫法:
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
list = query.list();
return list;
以原生SQL查詢的欄位必須符合entity的全部欄位
Spring Data JPA底層是Hiberante也必須符合此規則
https://matthung0807.blogspot.com/2021/01/spring-data-jpa-nativequery-sqlgrammerexception-could-not-execute-query.html