[英]Can hibernate convert one pojo data into the another pojo with few fields
I have two entities: 我有两个实体:
POJO 1: POJO 1:
@Entity
@Table(name = "tasks")
Class Task{
@Id
@Column(name = "id")
private String id ;
private String claimedId;
private String name ;
private Date date;
// gets etc...
}
and 和
POJO 2: POJO 2:
@Entity
@Table(name = "calimtask")
Class ClaimTask{
String id ;
String claimedId;
String name;
// gets etc...
}
POJO 2 is created with some fields of POJO 1. We have data for Task table in database. POJO 2是使用POJO 1的某些字段创建的。数据库中有Task表的数据。
Is it possible that Hibernate can get data of id,claimedId and name using POJO 1 and could convert into the POJO 2? Hibernate是否有可能可以使用POJO 1获取id,claimedId和name的数据并转换为POJO 2?
You should never attempt to convert an Entity class from one Entity to another since each entity represents a Table. 您永远不要尝试将Entity类从一个实体转换为另一个实体,因为每个实体都代表一个表。
Hibernate however provides a means to return POJO2
as an Object from the Columns selected using Hibernate Transformers
class. 但是,Hibernate提供了一种从使用Hibernate
Transformers
类选择的列中返回POJO2
作为对象的方法。 In your case, you will need to write a custom POJO2
with getter setter of the columns you are returning. 对于您的情况,您将需要使用要返回的列的getter setter编写自定义
POJO2
。 Note that is is important that the variables be named exactly like the alias columns. 请注意,变量的名称必须与别名列完全一样,这一点很重要。
public static List<ClaimTask> getDetailsfromTask(){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
List<ClaimTask> list = new ArrayList<ClaimTask>();
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Task.class);
cr.setProjection(Projections.projectionList()
.add......;//Pick all the columns you need from Task
cr.setResultTransformer(Transformers.aliasToBean(ClaimTask.class));
list = (List<ClaimTask>) cr.list();
}catch (Exception asd) {
System.out.println(asd.getMessage());
if (tx != null) {
tx.rollback();
}
} finally {
session.close();
}
return list;
}
Please note that the properties in ClaimTask
should be named the same as the column aliases you pull from Task
. 请注意,
ClaimTask
中的属性应与您从Task
提取的列别名相同。 Make sure also that ClaimTask
is just plain getter
setter
class not an entity Class. 同时确保
ClaimTask
只是普通的getter
setter
类,而不是实体Class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.