3 回答
TA贡献1828条经验 获得超4个赞
SqlResultSetMapping
ColumnResult
TA贡献1836条经验 获得超5个赞
使用映射实体(JPA2.0)
Query query = em.createNativeQuery("SELECT name,age FROM jedi_table", Jedi.class);@SuppressWarnings("unchecked")List<Jedi> items = (List<Jedi>) query.getResultList();
Jedi
@NamedNativeQuery( name="jedisQry", query = "SELECT name,age FROM jedis_table", resultClass = Jedi.class)
TypedQuery<Jedi> query = em.createNamedQuery("jedisQry", Jedi.class);List<Jedi> items = query.getResultList();
人工映射
public static <T> T map(Class<T> type, Object[] tuple){ List<Class<?>> tupleTypes = new ArrayList<>(); for(Object field : tuple){ tupleTypes.add(field.getClass()); } try { Constructor<T> ctor = type.getConstructor(tupleTypes.toArray(new Class<?>[tuple.length])); return ctor.newInstance(tuple); } catch (Exception e) { throw new RuntimeException(e); }}
public static <T> List<T> map(Class<T> type, List<Object[]> records){ List<T> result = new LinkedList<>(); for(Object[] record : records){ result.add(map(type, record)); } return result;}public static <T> List<T> getResultList(Query query, Class<T> type){ @SuppressWarnings("unchecked") List<Object[]> records = query.getResultList(); return map(type, records);}
Query query = em.createNativeQuery("SELECT name,age FROM jedis_table");List<Jedi> jedis = getResultList(query, Jedi.class);
带有@SqlResultSetmap的JPA2.1
@SqlResultSetMapping(name="JediResult", classes = { @ConstructorResult(targetClass = Jedi.class, columns = {@ColumnResult(name="name"), @ColumnResult(name="age")})})
Query query = em.createNativeQuery("SELECT name,age FROM jedis_table", "JediResult");@SuppressWarnings("unchecked")List<Jedi> samples = query.getResultList();
Jedi
使用XML映射
@SqlResultSetMapping
META-INF/orm.xml
<named-native-query name="GetAllJedi" result-set-mapping="JediMapping"> <query>SELECT name,age FROM jedi_table</query></named-native-query><sql-result-set-mapping name="JediMapping"> <constructor-result target-class="org.answer.model.Jedi"> <column name="name" class="java.lang.String"/> <column name="age" class="java.lang.Integer"/> </constructor-result> </sql-result-set-mapping>
添加回答
举报