在使用hibernate过程,对于复杂的查询,还是得使用sql语句来查询,但是查询出来的数据如何装载到bean中,因为查出来的数据可能会是关联好几个表里字段,对于这种情况,如何将这些字段直接装载到java bean中呢。下面给出一个例子,希望对大家有帮助。
实体类:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
@Entity
//表名与类名不相同时重新定义表名.
@Table(name = "demo")
//默认的缓存策略.
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Demo {
@Id
@Column(length = 32)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id;
@Column(nullable =true)
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
SQL语句:
List list = this.getSession().createSQLQuery("select bankcar_id id ,carname name from Bankcar")
.addEntity(Demo.class).list();
for (int i = 0; i < list.size(); i++) {
Demo d = (Demo)list.get(i);
System.out.println(d.getId());
}
这个例子只是为了说明问题,没有实际的意义。
通过SQL语句中的别名可以装载到其他对象中的bean属性,只要名字一样就行。
还有,如果名字有重复的,那么以第一次出现的那个名字的值为准,后面的值将被忽略。