9.3.原生查询
EJB QL中富有大量的查询语句并且基本上能符合你的绝大多数的查询需求.有时,你想要使用特定厂商提供的数据库上的专有能力.
实体管理服务提供了一个方法来建立原生的SQL查询并且映射他们到你的对象上.原生查询能反回实体,栏位值,或者两者的组合.EntityManager接口有三种方法来建立原生查询:一种返回标量值,一种是返回实体类型,最后一种是定义一个复杂的结果集,它能映射到多个实体的混合和标量值.
你可以进行JDBC的连接通过javax.sql.DataSource,使用@Resource注入和执行你的SQL语句.要意识到你所做的改变不会被当前的持久化上下文所反映.
9.3.1. 标量原生查询
Query createNativeQuery(String sql)
这将建立一个原生查询返回一个标量结果.它需要一个参数:你的原生SQL.它执行并且返回结果集同EJB QL相同的形式,返回标量值.
9.3.2.简单的实体原生查询
Query createNativeQuery(String sql, Class entityClass)
一个简单的原生查询通过一个SQL语句和隐式的映像到一个实体,映射元数据为基础的一个实体.它认为原生查询的结果集中的栏将完全匹配实体的O/R映射.原生SQL查询的映射实体的确定通过entityClass 参数:
Query query = manager.createNativeQuery(
"SELECT p.phone_PK, p.phone_number, p.type
FROM PHONE AS p", Phone.class
);
实体的所有属性被列出:
9.3.3.复杂的原生查询
这个实体管理方法允许你有一个复杂的映射为原生SQL.你可以同时返回多个实体和标量栏.mappingName 参数参考@javax.persistence.SqlResultSetMapping定义.这个批注用来定义一个怎能样查询原生结果的钓子到O/R模型.如果返回的栏位名与批注映射的属性不匹配,你可以提代一个字段到栏位的映射为他们,使用@javax.persistence.FieldResult :
package javax.persistence;
public @interface SqlResultSetMapping {
String name( );
EntityResult[] entities( ) default {};
ColumnResult[] columns( ) default {};
}
public @interface EntityResult {
Class entityClass( );
FieldResult[] fields( ) default {};
String discriminatorColumn( ) default "";
}
public @interface FieldResult {
String name( );
String column( );
}
public @interface ColumnResult {
String name( );
}
让我们做一系列的例子表示这会如何工作.
9.3.3.1. 使用多个实体的原生查询
@Entity
@SqlResultSetMapping(name="customerAndCreditCardMapping",
entities={@EntityResult(entityClass=Customer.class),
@EntityResult(entityClass=CreditCard.class,
fields={@FieldResult(name="id",
column="CC_ID"),
@FieldResult(name="number",
column="number")}
)})
public class Customer {...}
// execution code
{
Query query = manager.createNativeQuery(
"SELECT c.id, c.firstName, cc.id As CC_ID,
cc.number" +
"FROM CUST_TABLE c, CREDIT_CARD_TABLE cc" +
"WHERE c.credit_card_id = cc.id",
"customerAndCreditCardMapping");
}
因为结果集返回多个实体类型,我们必需使用一个@SqlResultSetMapping.这个批注可以被放在一个实体类或方法上.entities( )属性用来设置@EntityResult批注组成的队列.每一个@EntityResult注释指定将要通过原生SQL查询返回的实体.
@javax.persistence.FieldResult注释用来明确查询中与实体属性对应的映射栏位.@FieldResult批注的name()属性标识实体组件的属性, column( ) 属性标识通过原生查询返回的结果集栏位.
在这个例子中,我们需要指定@FieldResults为客户.原生查询为实体引用的每一个栏位.因为我们只查询CreditCard 实体的ID和number栏,@FieldResult批注需要被指定.在 CreditCard的@EntityResult批注中,fields()属性定义CreditCard 属性每次查询的映射.因为Customer和CreditCard主键栏有相同的名子,SQL查询需要辨别出他们的不同.cc.id As CC_ID这段SQL代码演示出这种标识.
我们也可以使用XML来表达:
<entity-mappings>
<sql-result-set-mapping name="customerAndCreditCardMapping">
<entity-result entity-class="com.titan.domain.Customer"/>
<entity-result entity-class="com.titan.domain.CreditCard"/>
<field-result name="id" column="CC_ID"/>
<field-result name="number" column="number"/>
</entity-result>
</sql-result-set-mapping>
</entity-mappings>
9.3.3.2.混合标量和实体结果
在我们的最终例子,显示一个实体和一个标量值的混合.我们写一个原生查询,来返回一个每次巡行由多少预定组成的巡行列表.
@SqlResultSetMapping(name="reservationCount",
entities=@EntityResult(name="com.titan.domain.Cruise",
fields=@FieldResult(name="id", column="id")),
columns=@ColumnResult(name="resCount"))
@Entity
public class Cruise {...}
{
Query query = manager.createNativeQuery(
"SELECT c.id, count(Reservation.id) as resCount
FROM Cruise c LEFT JOIN Reservation ON c.id = Reservation.CRUISE_ID
GROUP BY c.id",
"reservationCount");
}
reservationCount映射的定义,原生查询表现对一个巡航实体和一个所有巡航预定的数目的请求.@FieldResult批注标识c.id栏同Cruise实体相关联.@ColumnResult批注标识resCount栏同一个标量值.
等价的XML文件:
<entity-mappings>
<sql-result-set-mapping name="reservationCount">
<entity-result entity-class="com.titan.domain.Cruise">
<field-result name="id" column="id"/>
</entity-result>
<column-result name="resCount"/>
</sql-result-set-mapping>
</entity-mappings>
9.4命名查询
JAVA持久化提供了一种机制,所以在建立一个查询时,你可以预先定义EJB QL或原SQL查询,并且引用它们通过名字.你可以先建立查询,然后建立JAVA语言中的String类型的常量:在多种不同的情形中重复使用他们.你预先定义一个查询,当在后面用到的时候,可以很容易的进行调整.@javax.persistence.NamedQuery 批注用在预定义EJB QL中:
package javax.persistence;
public @interface NamedQuery {
String name( );
String query( );
QueryHint[] hints( ) default {};
}
public @interface QueryHint {
String name( );
String value( );
}
public @interface NamedQueries {
NamedQuery[] value( );
}
当你定义一个或多个查询在类或包中,你可以使用@javax.persistence.NamedQueries 批注.@javax.persistence.QueryHint批注定义厂商提供的暗示.这些暗示工作方式与Query.setHint( )方法类似,它的描述在本单的前面.这是一个例:
package com.titan.domain;
import javax.persistence.*;
@NamedQueries({
@NamedQuery
(name="getAverageReservation",
query=
"SELECT AVG( r.amountPaid)
FROM Cruise As c, JOIN c.reservations r
WHERE c = :cruise"),
@NamedQuery(name="findFullyPaidCruises",
query=
"FROM Cruise cr
WHERE 0 < ALL (
SELECT res.amountPaid from cr.reservations res
)")
})
@Entity
public class Cruise {...}
在这个例子中定义了两个EJB QL查询在Cruise实体组件类.你可以引用这些定义在EntityManager.createNamedQuery( )方法中:
Query query = em.createNamedQuery("findFullyPaidCruises");
Query.setParameter("cruise", cruise);
等价于@NamedQuery的XML文件:
<entity-mappings>
<named-query
name="getAverageReservation">
<query>
SELECT AVG( r.amountPaid)
FROM Cruise As c JOIN c.reservations r
WHERE c = :cruise
</query>
</named-query>
</entity-mappings>
9.4.1.命名原生查询
@javax.persistence.NamedNativeQuery 批注用于预处理原生SQL查询:
package javax.persistence;
public @interface NamedNativeQuery {
String name( );
String query( );
Class resultClass( ) default void.class;
String resultSetMapping( ) default "";
}
public @interface NamedNativeQueries {
NamedNativeQuery[] value( );
}
resultClass() 属性是为当你有一个原生查询时,只返回一个实体类型.(看这章的前面"Native Queries" 节).resultSetMapping( ) 属性解决一个预定@SqlResultSetMapping.这两个属性是可选的,但是你必需至少定义它们中的一个.这是@NamedNativeQuery批注的一个例子:
@NamedNativeQuery(
name="findCustAndCCNum",
query="SELECT c.id, c.firstName, c.lastName, cc.number AS CC_NUM
FROM CUST_TABLE c, CREDIT_CARD_TABLE cc
WHERE c.credit_card_id = cc.id",
resultSetMapping="customerAndCCNumMapping")
@SqlResultSetMapping(name="customerAndCCNumMapping",
entities={@EntityResult(entityClass=Customer.class)},
columns={@ColumnResult(name="CC_NUM")}
)
@Entity
public class Customer {...}
你可以参考EntityManager.createNamedQuery( ) 的定义:
Query query = em.createNamedQuery("findCustAndCCNum");
等价的XML文件:
<entity-mappings>
<named-native-query name="findCustAndCCNum"
result-set-mapping="customerAndCCNumMapping"/>
<query>
SELECT c.id, c.firstName, c.lastName,
cc.number AS CC_NUM
FROM CUST_TABLE c, CREDIT_CARD_TABLE cc
WHERE c.credit_card_id = cc.id
</query>
</named-native-query>
</entity-mappings>
Phone实体中加入
@NamedNativeQuery(name="NativePhone",
query="SELECT p.phone_PK, p.phone_number, p.type FROM PHONE AS p",
resultClass=Phone.class)
Named Native Query, implicit mapping
--------------------------------
Executing @NamedNativeQuery(name="NativePhone")
Exception in thread "main" javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:50)
at com.lyh.ejb3.clients.NativeQueries.main(NativeQueries.java:42)
Initialize DB
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.MappingException: Named query not known: NativePhone
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:567)
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:90)
at com.lyh.ejb3.clients.NativeQueries.nativeSql(NativeQueries.java:54)
at com.lyh.ejb3.clients.NativeQueries.main(NativeQueries.java:34)
Caused by: org.hibernate.MappingException: Named query not known: NativePhone
Named Native Query, implicit mapping
--------------------------------
Executing @NamedNativeQuery(name="NativePhone")
at org.hibernate.impl.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:70)
at org.hibernate.impl.SessionImpl.getNamedQuery(SessionImpl.java:1260)
at org.hibernate.ejb.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:87)
... 2 more
Customer实体中加入
@Table(name="CUST_TABLE")
@SqlResultSetMapping(name="customerAndCreditCardMapping",
entities={@EntityResult(entityClass=Customer.class),
@EntityResult(entityClass=CreditCard.class,
fields={@FieldResult(name="id", column="CC_ID"),
@FieldResult(name="number", column="number")}
)})
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown SqlResultSetMapping [customerAndCreditCardMapping]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:567)
at org.hibernate.ejb.AbstractEntityManagerImpl.createNativeQuery(AbstractEntityManagerImpl.java:128)
at com.lyh.ejb3.clients.NativeQueries.nativeWithMultipleEntities(NativeQueries.java:74)
at com.lyh.ejb3.clients.NativeQueries.main(NativeQueries.java:36)
Caused by: org.hibernate.MappingException: Unknown SqlResultSetMapping [customerAndCreditCardMapping]
at org.hibernate.impl.SQLQueryImpl.setResultSetMapping(SQLQueryImpl.java:290)
at org.hibernate.ejb.AbstractEntityManagerImpl.createNativeQuery(AbstractEntityManagerImpl.java:124)
... 2 more
加入@Table(name="CREDIT_CARD_TABLE") 并在相应属性加入@Column批注
ERROR - Table 'titan.credit_card_table' doesn't exist
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2147)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2028)
at org.hibernate.loader.Loader.list(Loader.java:2023)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:150)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:53)
... 2 more
强制类型转换
Exception in thread "main" java.lang.ClassCastException: java.math.BigInteger
at com.lyh.ejb3.clients.NativeQueries.mixedNative(NativeQueries.java:109)
at com.lyh.ejb3.clients.NativeQueries.main(NativeQueries.java:38)