19

1 2: select (table.*)/(all column) 就OK了

String sql = "select t_student.* from t_student";
//String sql = "select t_student.id,t_student.name,... from t_student"; //select all column
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Student.class);//or query.addEntity("alias", Student.class);
//query.list();[Student@..., Student@..., Student@...]
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); //or other transformer
query.list(); //[{Student(or alias)=Student@...},{Student=Student@...}]

3:选择一些列(不是全部),是错误

String sql = "select t_student.id,t_student.name.t_student.sex from t_student";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Student.class);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
query.list(); //Exception:invalid column/no column

我希望“3”可以正常工作,并让结果可以映射到 Student.class。
喜欢:Student[id=?, name=?, sex=?, (other field are null/default)]
我不知道这个错误,请帮帮我!

4

5 回答 5

25

您可以进一步添加 .setResultTransformer(Transformers.aliasToBean(YOUR_DTO.class)); 并自动将其映射到您的自定义 dto 对象,另请参阅返回非托管实体

例如:

public List<MessageExtDto> getMessagesForProfile2(Long userProfileId) {
    Query query = getSession().createSQLQuery("  "
            + " select a.*, b.* "
            + " from messageVO AS a "
            + " INNER JOIN ( SELECT max(id) AS id, count(*) AS count FROM messageVO GROUP BY messageConversation_id) as b ON a.id = b.id "
            + " where a.id > 0 "
            + " ")
            .addScalar("id", new LongType())
            .addScalar("message", new StringType())
            ......... your mappings
            .setResultTransformer(Transformers.aliasToBean(MessageExtDto.class));

    List<MessageExtDto> list = query.list();
    return list;
}
于 2014-02-13T15:03:39.417 回答
4

我希望“3”正常工作,并让结果可以映射到 Student.class

这是可能的使用
Query createNativeQuery(String sqlString, String resultSetMapping

在第二个参数中,您可以告诉结果映射的名称。例如:

1) 让我们考虑一个Student实体,魔术将在 SqlResultSetMapping 注释中:

import javax.persistence.Entity;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.Table;

@Entity
@Table(name = "student")
@SqlResultSetMapping(name = "STUDENT_MAPPING", classes = {@ConstructorResult(
    targetClass = Student.class, columns = {
      @ColumnResult(name = "name"),
      @ColumnResult(name = "address")
})})
public class Student implements Serializable {
   private String name;
   private String address;

   /* Constructor for the result mapping; the key is the order of the args*/ 
   public Student(String aName, String anAddress) {
       this.name = aName;
       this.address = anAddress;
   }

   // the rest of the entity
}

2)现在您可以执行查询,其结果将按STUDENT_MAPPING逻辑映射:

String query = "SELECT s FROM student s";
String mapping = "STUDENT_MAPPING";
Query query = myEntityManager.createNativeQuery(query, mapping);
@SuppressWarnings("unchecked")
List<Student> students = query.getResultList();
for (Student s : students) {
   s.getName(); // ...
}

注意:我认为无法避免未经检查的警告。

于 2015-03-29T12:06:18.960 回答
3

只有两种方法。

您可以使用第一个或第二个片段。根据 Hibernate 文档,您必须更喜欢 2nd。

您可以只获取对象数组的列表,如下所示:

String sql = "select name, sex from t_student";
SQLQuery query = session.createSQLQuery(sql);
query.addScalar("name", StringType.INSTANCE); 
query.addScalar("sex", StringType.INSTANCE); 
query.list();
于 2013-06-28T04:13:21.833 回答
1

我在 HQL 查询上遇到了同样的问题。我通过更换变压器解决了这个问题。

该问题导致编写的代码转换为 Map。但它不适用于 Alias Bean。您可以在下面看到错误代码。将结果转换为地图并将新字段放入地图的代码。

类:org.hibernate.property.access.internal.PropertyAccessMapImpl.SetterImpl m 方法:set

    @Override
    @SuppressWarnings("unchecked")
    public void set(Object target, Object value, SessionFactoryImplementor factory) {
        ( (Map) target ).put( propertyName, value );
    }

我解决了复制变压器并更改代码的问题。

您可以在项目中看到代码。

链接:https ://github.com/robeio/robe/blob/DW1.0-migration/robe-hibernate/src/main/java/io/robe/hibernate/criteria/impl/hql/AliasToBeanResultTransformer.java

班级:

import java.lang.reflect.Field;
import java.util.Map;

import io.robe.hibernate.criteria.api.query.SearchQuery;
import org.hibernate.HibernateException;
import org.hibernate.transform.AliasedTupleSubsetResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AliasToBeanResultTransformer extends AliasedTupleSubsetResultTransformer {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliasToBeanResultTransformer.class);

    private final Class resultClass;

    // Holds fields of Transform Class as Map. Key is name of field. 
    private Map<String, Field> fieldMap;

    public AliasToBeanResultTransformer(Class resultClass) {
        if ( resultClass == null ) {
            throw new IllegalArgumentException( "resultClass cannot be null" );
        }
        fieldMap = SearchQuery.CacheFields.getCachedFields(resultClass);
        this.resultClass = resultClass;
    }

    @Override
    public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
        return false;
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        Object result;
        try {
            result = resultClass.newInstance();
            for ( int i = 0; i < aliases.length; i++ ) {
                String name = aliases[i];
                Field field = fieldMap.get(name);

                if(field == null) {
                    LOGGER.error(name + " field not found in " + resultClass.getName() + " class ! ");
                    continue;
                }
                field.set(result,  tuple[i]);
            }
        }
        catch ( InstantiationException e ) {
            throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
        } catch ( IllegalAccessException e ) {
            throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
        }

        return result;
    }
}

创建新变压器后,您可以使用如下所示。

query.setResultTransformer(new AliasToBeanResultTransformer(YOUR_DTO.class));
于 2016-12-07T12:37:33.820 回答
0

您可以自动映射它:

  1. 您的模型 Student.java

    公共类学生{私人字符串名称;私有字符串地址;}

  2. 存储库

    String sql = "Select * from student"; 查询查询 = em.createNativeQuery(sql, Student.class); 列表 ls = query.getResultList();

  • 所以它会自动将结果映射到 Student 类
于 2021-04-24T05:24:21.670 回答