Spring与Hibernate Dao中操作数据库的另外方式

来源:互联网 发布:部队mdm软件下载 编辑:程序博客网 时间:2024/06/10 07:08
  1. // search Person Object
  2.     /**
  3.      * @param firstname
  4.      * @param lastname
  5.      * @return
  6.      */
  7.     public List searchPerson(final String firstname, final String lastname) {
  8.         return getHibernateTemplate().executeFind(new HibernateCallback() {
  9.             public Object doInHibernate(Session session)
  10.                     throws HibernateException, SQLException {
  11.                 List list = new ArrayList();
  12.                 String sql = " select  pid,firstname,lastname   from person where  firstname like  '"
  13.                         + firstname
  14.                         + "%' and lastname like '"
  15.                         + lastname
  16.                         + "%' order by  lastname;";
  17.                 PreparedStatement pstmt = null;
  18.                 Connection conn = null;
  19.                 ResultSet rs = null;
  20.                 try {
  21.                     conn = session.connection();
  22.                     pstmt = conn.prepareStatement(sql);
  23.                     rs = pstmt.executeQuery();
  24.                     while (rs != null && rs.next()) {
  25.                         String pid = rs.getString(1);
  26.                         String firstname = rs.getString(2);
  27.                         String lastname = rs.getString(3);
  28.                         Person person = new Person();
  29.                         person.setPid(pid);
  30.                         person.setFirstname(firstname);
  31.                         person.setLastname(lastname);
  32.                         list.add(person);
  33.                     }
  34.                 } catch (Exception e) {
  35.                     log.error(e);
  36.                 } finally {
  37.                     try {
  38.                         if (rs != null)
  39.                             rs.close();
  40.                     } catch (Exception e) {
  41.                         log.error(e);
  42.                     } finally {
  43.                         try {
  44.                             if (pstmt != null)
  45.                                 pstmt.close();
  46.                         } catch (Exception e) {
  47.                             log.error(e);
  48.                         }
  49.                     }
  50.                 }
  51.                 return list;
  52.             }
  53.         });
  54.     }
原创粉丝点击