1、dao,查出指定字段
public List<A> getInfo() {
String hql="select new A(b.id,b,name) from B b";//实体类A必须有两个参数的构造函数
Session session=getSession();
List<A>list=null;
try {
Query query=session.createQuery(hql);
list=query.list();
} catch (RuntimeException e) {
throw e;
}finally{
session.close();
}
return list;
}
2、实体类A,保存指定要查询的信息
public class A{
private Integer id;//注意,这里不要用int
private String name;
public MsgPackages() {
}
public MsgPackages(Integer id,String name){//带两个参数的构造函数
this.id=id;
this.name=name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3、建一个简单的A.hbm.xml,这个是重点,用于解决“Unable to locate class”问题
<pre name="code" class="java"><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.entity">
<import class="MsgPackages"/>
</hibernate-mapping>
4、修改配置文件
由于我是SSH整合框架,直接在applicationContext.xml中添加配置文件
<property name="mappingResources">
<list>
<value>com/entity/A.hbm.xml</value>
</list>
</property>