将数据库的数据封装成对象-java

由于调用hibernate封装对象,会自动调用联级查询。而我需要用一个左联接sql来减少访问数据库的耗时,所以我自己封装数据成对象。


    public List findByClassld(Integer classId,int startIndex,int size) throws ParseException{
        if(classId != null&&classId != 0){
            Long t1 = new Date().getTime();
            Session session = sessionFactory.openSession();
            String sql = "select t1.id," +
                    "t1.capture," +
                    "t1.context," +
                    "t1.author," +
                    "t1.create_time," +
                    "t1.class_id," +
                    "t2.news_class_context" +
                    " from t_news t1 " +
                    "LEFT JOIN news_class_attr t2 " +
                    "on t2.news_class_id= t1.class_id " +
                    "where t1.class_id = "+ classId 
                    +" limit " +startIndex+", "+size;
            List resultList = new ArrayList();
            List list = session.createSQLQuery(sql).list();
            Long t2 = new Date().getTime();
            for (Object[] obj : list) {

                if(obj[4]!=null){
                    obj[4] = obj[4].toString();
                }
                resultList.add(new TNews(
                        (Integer)obj[0],
                        (String)obj[1],
                        (String)obj[2],
                        (String)obj[3],
                            (Date)obj[4],
                        (Integer)obj[5],
                        new NewsClassAttr(null,(String)obj[6])));
            }
            session.flush();
                        session.close();
            return resultList;
        }
        return null;    
    }

你可能感兴趣的:(将数据库的数据封装成对象-java)