转 http://blog.163.com/ksm19870304@126/blog/static/374552332011993942391/
配置方式:
static List namedQuery(int id) {
Session s = HibernateUtil.getSession();
Query q = s.getNamedQuery("getUserById");
q.setInteger("id", id);
return q.list();
}
<! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
< hibernate-mapping >
< class name ="com.sy.vo.User" table ="user" catalog ="news" >
</ class >
<!-- 命名查询:定义查询条件 -->
< query name ="getUserById" >
<![CDATA[ from User where id=:id ]]>
</ query >
<!-- 命名查询中使用sql,不推荐使用,影响跨数据库
<sql-query name="getUserById2">
<![CDATA[select * from User where ]]>
</sql-query> -->
</ hibernate-mapping >
标注方式:
标注方式是我们项目中用到的
,@Entity
@NamedQueries( {
@NamedQuery(name="Trade.findTotalPaymentAndBuyerNum",
query = "select sum(payment),count(distinct t.buyerNick),sum(t.postFee),sum(t.num) from Trade t where t.payTime >= :start and t.payTime < :end and t.sellerNick = :sellerNick"),
@NamedQuery(name="Trade.findCreatedPayments",
query = "select sum(payment),count(distinct t.buyerNick),sum(t.num) from Trade t where t.created >= :start and t.created < :end and t.sellerNick = :sellerNick")})
public class Trade {
。。。。
}
放在了类的前面,可以多个,有name跟query两个属性,而且query里面已经有了‘:start’这样的可以传递参数的。
其中一个Service的实现里面可以这样用:
public Object[] getTotalPaymentAndBuyerNum(String sellerNick, Date start, Date end) {
Map<String, Object> queryParams = new HashMap<String, Object>();
queryParams.put("sellerNick", sellerNick);
queryParams.put("start", start);
queryParams.put("end", end);
List list = genericDao.findByNamedQuery("Trade.findTotalPaymentAndBuyerNum", queryParams);
Object[] o = (Object[]) list.get(0);
return o;
}
genericDao的实现是继承了HibernateDaoSupport的:
public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
String[] params = new String[queryParams.size()];
Object[] values = new Object[queryParams.size()];
int index = 0;
Iterator<String> i = queryParams.keySet().iterator();
while (i.hasNext()) {
String key = i.next();
params[index] = key;
values[index++] = queryParams.get(key);
}
return getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, params, values);
}
适用情况:万能方法,有点像ibatis轻量级框架的操作,方便维护。 缺点:不面向对象。基于hql和sql,有一定缺陷,第二种标注方式更简单易用,最主要是扩展性很强的,推荐用第二种方式方便开发。
转http://hi.baidu.com/echo_weng/item/60303e2d067578d20e37f999
hibernate 存储过程的使用
实体:
@Entity
@NamedQuery(name = "getAll", query = "from NetUser")
@NamedNativeQueries(value = {
@NamedNativeQuery(name = "getList", query = "{call select_allnetuser}", resultClass = NetUser.class),
@NamedNativeQuery(name = "getById", query = "{call select_netUserById(:id)}", resultClass = NetUser.class)
})
@Table(name = "netuser")
public class NetUser {
@Id
@GeneratedValue
private Long id;
@Column(name = "username", unique = true, nullable = false)
private String username;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "email")
private String email;
@Column(name = "telephone")
private String telephone;
@Column(name = "address")
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
//Dao
public class NetUserDaoImpl extends BaseDaoSupport<NetUser> implements NetUserDao {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List<NetUser> getAll() {
return getHibernateTemplate().findByNamedQuery("getList");
}
@Override
public NetUser getById(Long id){
return (NetUser) getHibernateTemplate().findByNamedQueryAndNamedParam("getById", "id", id).get(0);
}
}
测试类:
protected void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("application.hibernate.xml");
netUserDao = (NetUserDao) ctx.getBean("netUserDao");
super.setUp();
}
@SuppressWarnings("unchecked")
public void testProcedure(){
List<NetUser> netUsers = netUserDao.getAll();
for(NetUser netUser : netUsers){
System.out.println(netUser);
}
}
public void testGetById(){
System.out.println(netUserDao.getById(2L));
}