架构师之hibernate实体注解------实体如何用setResultTransformer转换?
1.前言.
当你用hibernate查出数据,但是类型不是原来的类型怎么办,新增的实体类还用不用,答案是可以用的.用query.setResultTransformer(Transformers.aliasToBean(AA.class));这种形式可以解决查出来的数据不能使用的问题.
2.代码
(1)查询dao String sql = "select USER_ID,USERNAME from test where USER_ID= :id"; Query query = getCurrentSession().createSQLQuery(sql);//.addScalar("MODULE_ID", LongType.INSTANCE); query.setBigDecimal("id", new BigDecimal("1")); query.setResultTransformer(Transformers.aliasToBean(UserEntity.class)); List<UserEntity> list=null; list=query.list(); return list;
(2)实体类
package com.test.ljn.sample.domain; import java.math.BigDecimal; import java.math.BigInteger; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import com.test.ljn.base.domain.IBean; import javax.persistence.Table; import org.hibernate.annotations.PolymorphismType; import org.hibernate.annotations.Polymorphism; @Entity @Table(name = "test_USER") @Polymorphism(type = PolymorphismType.EXPLICIT) public class UserEntity implements IBean<Long> { /** * */ private static final long serialVersionUID = 1L; /** 模块ID */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "USER_ID", unique = true, nullable = false) private BigInteger USER_ID; /** 父模块ID */ @Column(name = "USERNAME") private String USERNAME; public BigInteger getUSER_ID() { return USER_ID; } public void setUSER_ID(BigInteger uSER_ID) { USER_ID = uSER_ID; } public String getUSERNAME() { return USERNAME; } public void setUSERNAME(String uSERNAME) { USERNAME = uSERNAME; } }
3.需要注意的.
(1)这种转换实体类很严格,必须连属性名字要和数据库字段高度一致(注解此时没很大作用用.
(2)实体类可以比表字段少一些字段.