I have a table: User开发者_开发知识库 with columns: { id, name, address}
I want to use hibernate to select only the id from this table. But i don't want to use HQL for native SQL query. I want to use the Criteria object. Is there a way to do that?
Thanks,
Sean Nguyen
Yes. You have to use a Projection :
Criteria c = session.createCriteria(User.class, "u");
c.setProjection(Projections.property("u.id"));
return c.list(); // the list of all the user IDs
But HQL is much more readable and straightforward for this kind of query. Criteria is useful for dynamically built queries, or to reuse parts of queries in several ones :
return session.createQuery("select u.id from User u").list();
It is possible to apply a ResultTransformer to native SQL queries, allowing it to return non-managed entities.
as an example, say we have entdemodetail entity like below
@Entity
@Table(name = "demodetail")
public class EntDemodetail {
Integer id;
String description;
Integer demoid;
EntDemo demo;
@Id
@GeneratedValue
@Column(name = "id_detail", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="detaildesc")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name="demoid")
public Integer getDemoid() {
return demoid;
}
public void setDemoid(Integer demoid) {
this.demoid = demoid;
}
@OneToOne()
@JoinColumn(name="demoid")
public EntDemo getDemo() {
return demo;
}
public void setDemo(EntDemo demo) {
this.demo = demo;
}
}
you can read some columns of this entity like below
/* Method to READ some columns of an entity with native sql */
public void nativesqlwithresulttransformer( ){
Session session = HibernateUtilMysql.getSessionFactory().openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
String sql = "SELECT id_detail as id FROM demodetail d"; //
SQLQuery query = session.createSQLQuery(sql);
List results = query.setResultTransformer(Transformers.aliasToBean(EntDemodetail.class)).list();
for (Iterator iterator =
results.iterator(); iterator.hasNext();){
EntDemodetail entdemodetail = (EntDemodetail) iterator.next();
System.out.print("Id: " + entdemodetail.getId());
//System.out.print("Desc: " + entdemodetail.getDescription());
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
for more information , you can see http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/querysql.html
精彩评论