DTO-数据传输对象;pojo-最纯粹的java对象与数据库中的表一一对应。
简单讲:DTO起到业务数据的传递作用,pojo则与持久层数据库打交道。
有时候我们需要查询返回DTO对象,因为DTO封装我们操作此对象的业务方法;而这些业务方法从分层的思想上看不能封装到pojo中,因为这违背了hibernate编程规范,pojo(Plain Ordinary Java Object )是一个简单的普通Java对象,它不包含业务逻辑或持久逻辑。
hibernate查询返回DTO对象,DTO可能封装了多个pojo对象的属性和自己的业务方法;比如一个购物车的DTO可能封装了与购物车添加商品、移除商品等的方法。
上代码:
public AccountDTO getAccountByUsernameAndPassword(AccountDTO accountDTO) { String sql = "SELECT" + " SIGNON.USERNAME," + " ACCOUNT.EMAIL," + " ACCOUNT.FIRSTNAME," + " ACCOUNT.LASTNAME," + " ACCOUNT.STATUS," + " ACCOUNT.ADDR1," + " ACCOUNT.ADDR2," + " ACCOUNT.CITY," + " ACCOUNT.STATE," + " ACCOUNT.ZIP," + " ACCOUNT.COUNTRY," + " ACCOUNT.PHONE," + " PROFILE.LANGPREF," + " PROFILE.FAVCATEGORY," + " PROFILE.MYLISTOPT," + " PROFILE.BANNEROPT," + " BANNERDATA.BANNERNAME" + " FROM ACCOUNT, PROFILE, SIGNON, BANNERDATA" + " WHERE ACCOUNT.USERID = ?" + " AND SIGNON.PASSWORD = ?" + " AND SIGNON.USERNAME = ACCOUNT.USERID" + " AND PROFILE.USERID = ACCOUNT.USERID" + " AND PROFILE.FAVCATEGORY = BANNERDATA.FAVCATEGORY"; // Query query = this.getSession().createQuery(hql); //此方法有transaction的异常,因为我这里不是手动管理hibernate的事物,hibernate事物交给spring管理,此问题没能解决 // Query query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(aDTO.class)); Query query = this.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(AccountDTO.class)); query.setString(0, accountDTO.getUsername()); query.setString(1, accountDTO.getPassword()); return (AccountDTO) query.uniqueResult(); }
这里的重点方法:
Query query = this.getSession().createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(AccountDTO.class));
原生sql的查询,返回结果设置到DTO,hibernate给我们做了处理,类似与jdbc的查询这里可能用到了反射,所以要求DTO中的属性要与表字段名称相同,并且为全都小写。(我试图在sql中使用别名,而且DTO中属性使用了驼峰命名,但结果出错。网上有文章说:只需别名和属性名称一致即可;但我测试未成功。有经验的朋友请指教!)
搞完!