天天看点

Hibernate,爱你在心口难开。

1.多表查询问题大的很,除了用nativeSQL以外,还有三个解决办法:

   MEthod 1:

  private void testUseJDBCInHibernate() throws SQLException{

  Connection conn =super.getSession().connection();    //JDBC Connection

  String   sql="update   BBS_TOPIC     set   RESPONSE_NUM=RESPONSE_NUM+1   where   ID=?";

  PreparedStatement   ps =conn.prepareStatement(sql);

  ps.setInt(1, 1001);

  ps.execute();

 }

说明,当session里有了一个BO,假如你这个时候再去update或者insert,那么他会报错说,一个session里拥有多个不同的ReferenceID。这个时候你就得用JDBC的update语句来解决。

Method2:

 private List getTotalCharge(Date statTimeBegin,Date statTimeEnd){

  List res = new Vector();//将用于存放保存的结果集合

        Session session = null;

        ScrollableResults srs = null;

        session =super.getSession();

        srs = session.createQuery("select b.name, count(a.fee) mix(a.chargeBeginTime) max(a.chargeEndTime) from charge a, customer b where a.idCustomer = b.idCustomer and a.chargeBeginTime >= ? and a.chargeEndTime < ? gourp by a.idCustomer").setDate(0, statTimeBegin).setDate(1, statTimeEnd).scroll();

        //将查询结果放入List保存

        while(srs.next()){

            res.add(new TotalCharge(srs.getString(0), srs.getDouble(1), srs.getDate(2),srs.getDate(3)));

        }

  return res;

 }

Method3:

   在Hibernate中使用Apache的Commons_DB_util

   public List query(String sql,Class clazz){//clazz 为BO with setter and getter

           Connection conn = super.getSession().connection();    //JDBC Connection

           QueryRunner qRunner = new QueryRunner();

           List  beans = (List) qRunner.query(conn,sqlString,new BeanListHandler(clazz));

           return beans;

}