2011-11-24 27 views
9

Tôi có truy vấn bên dưới đang chọn hằng số trong danh sách cột và tôi đang mong đợi aliasToBean chuyển chuỗi thành loại enum thích hợp.Hibernate aliasToBean không chuyển đổi chuỗi thành Enum

Tôi đã ánh xạ các thực thể khác có thuộc tính enum dưới dạng Chuỗi và không gặp bất kỳ sự cố nào.

@SuppressWarnings("unchecked") 
    List<AssociatedEntity> fileList = queryUtil.createHQLQuery((
      "select '" + AssociatedEntityTypeEnum.ASSOCIATED_ENTITY_TYPE_FILE + "' as associatedEntityType," + 
      " a.file2Id as id," + 
      " f.name as name" + 
      " from File f, Association a" + 
      " where f.id = :fileId" + 
      " and a.file1Id = f.id" + 
      " and a.associationType = :associationType" 
    )) 
    .setParameter("fileId", fileId) 
    .setParameter("associationType", AssociationTypeEnum.ASSOCIATION_TYPE_FILE_FILE) 
    .setResultTransformer(Transformers.aliasToBean(AssociatedEntity.class)) 
    .list(); 

Đây là đậu:

public class AssociatedEntity { 

public AssociatedEntity() {} 

@Enumerated(EnumType.STRING) 
private AssociatedEntityTypeEnum associatedEntityType; 
public AssociatedEntityTypeEnum getAssociatedEntityType() { return this.associatedEntityType; } 
public void setAssociatedEntityType(AssociatedEntityTypeEnum associatedEntityType) { this.associatedEntityType = associatedEntityType; } 

private Integer id; 
public Integer getId() { return this.id; } 
public void setId(Integer id) { this.id = id; } 

private String name; 
public void setName(String name) { this.name = name; } 
public String getName() { return this.name; } 

} 

và đây là các lỗi:

23.11.2011 17:05:25 INFO [http-8080-2] (QueryUtil:createHQLQuery) - select 'ASSOCIATED_ENTITY_TYPE_FILE' as associatedEntityType, a.file2Id as id, f.name as name from File f, Association a where f.id = :fileId and a.file1Id = f.id and a.associationType = :associationType 
23.11.2011 17:05:25 ERROR [http-8080-2] (BasicPropertyAccessor$BasicSetter:set) - IllegalArgumentException in class: com.twoh.dto.AssociatedEntity, setter method of property: associatedEntityType 
23.11.2011 17:05:25 ERROR [http-8080-2] (BasicPropertyAccessor$BasicSetter:set) - expected type: com.twoh.dto.enums.AssociatedEntityTypeEnum, actual value: java.lang.String 

Trả lời

2

Đây là giải pháp tôi tìm thấy từ một trong các câu trả lời SO

Properties params = new Properties(); 
     params.put("enumClass", "models.IOStatusEnum"); 
     params.put("type", "12"); /*type 12 instructs to use the String representation of enum value*/ 
     Type myEnumType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, params); 
     SQLQuery q = sess.createSQLQuery(queryString).addScalar("status", myEnumType);; 
Các vấn đề liên quan