天天看點

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;

}