标签:property this org query class 垃圾 declared setter custom
大致结构:
Person(人): id,name,age,bookId
Book(书):id,bookName
Author(作者):id,authorName,bookId
一个人 只有 一本书,一本书 有多个 作者,一个作者 只出 一本书;(可能举例不好,明白就行)
Person ----> Book : OneToOne
Book ----> Author: OneToMany
期望达到的效果:
sql: select p.id id,p.name,b.bookName bookName from person p left join book b on p.bookId=b.id ;
不管这个person有没有book都要列出这个person
如果是规范的hibernate实体对象(不知道怎么描述规范,大致是符合hibernate面向对象的表设计的实体类)
sql相应的hql: select p.id id,p.name,b.bookName bookName from person p left join p.book b with p.bookId=b.id ; (有很多写法,但如果hibernate映射,我查到的说法是无法用hql写left join)
@Entity
@Table
public class Person{ private String id; private String name; private String age; @OneToOne private Book book; //... }
@Entity
@Table public class Book { private String id; private String bookName; @OneToOne private Person person; @OneToMany private List<Author> authors; //... } @Entity
@Table public class Author{ private String id; private String authorName; @ManyToOne private Book book; //... }
如果是这样,其实得到person就可以得到person的所有关联对象。但,如果考虑极致的查询效率、内存占用。那么(个人)感觉这做法不好。
较好的做法是,你要什么sql就返回什么指定的列映射到dto(所以,个人还是喜欢用ibatis/mybatis);
而且,现在遇到的问题是。实体对象Perosn中 private Book book; 写成了 private String bookId;导致hql无法达到left的效果(在没映射的关系下,反正没找到能达到left join效果的hql)。
所以,就用hibernate的sql来实现。(也可以用jdbcTmplate.query(…),只是分页是自己sql写好的;返回到自定义对象只要实现RowMapper就可以)
Demo:
String sql = "select p.id id ,p.name name ,b.bookName bookName from person p left join book b on p.bookId=b.id"; SQLQuery q = ....; //q.addScalar("id",StringType.INSTANCE); //q.addScalar("name",StringType.INSTANCE); //q.addScalar("bookName",StringType.INSTANCE); q.setResultTransformer(Transformers.aliasToBean(Dto.class));
问题:
用的数据库是oracle,所以导致默认获得到的别名alias都转成了大写。但是,在dto中又是驼峰式的。
所以,在Transformers中会报exception:can not find setter;
因为,Transformers是根据alias反射找到setter。但alias都是大写ID、NAME、BOOKNAME,但setter其实是setId、setName、setBookName。
解决:
1、sql中可以写成 select p.id “id” ,p.name “name” ,b.bookName “bookName” from person p left join book b on p.bookId=b.id ; 即sql中alias都加上双引号(oracle的规定),那么Transformers得到的alias不会被转换成大写。
2、设置addScalar(…),但个人觉得写的太多而且不通用,每个都要写。(最好加上类型)
3、重写/扩展oracle的dialect;
4、我也在博问发求助了:Hibernate原生sql查询多表返回自定义对象问题? ,又大致去查了下,在stackoverflow找到一个:mapping Hibernate query results to custom class? 重点看2L v.ladynev的回答,并且ta给了ta自己重写的transformers fluent-hibernate;
其实ta的做法和我在看transformers源码时想到的一样(本来以为代码量很少),既然是alias反射dto是找不到setter,那么就想办法找到setter;
public Object transformTuple(Object[] tuple, String[] aliases) { Object result; try { if ( ! isInitialized ) { initialize( aliases ); //exception } else { check( aliases ); } result = resultClass.newInstance(); for ( int i = 0; i < aliases.length; i++ ) { if ( setters[i] != null ) { setters[i].set( result, tuple[i], null ); } } } catch ( InstantiationException e ) { throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() ); } catch ( IllegalAccessException e ) { throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() ); } return result; } private void initialize(String[] aliases) { PropertyAccessor propertyAccessor = new ChainedPropertyAccessor( new PropertyAccessor[] { PropertyAccessorFactory.getPropertyAccessor( resultClass, null ), PropertyAccessorFactory.getPropertyAccessor( "field" ) } ); this.aliases = new String[ aliases.length ]; setters = new Setter[ aliases.length ]; for ( int i = 0; i < aliases.length; i++ ) { String alias = aliases[ i ]; if ( alias != null ) { this.aliases[ i ] = alias; setters[ i ] = propertyAccessor.getSetter( resultClass, alias ); //exception: alias都是大写,再深入看propertyAccessor.getSetter就知道是找不到setter } } isInitialized = true; }
// org.hibernate.property.BasicPropertyAccessor private static Method setterMethod(Class theClass, String propertyName) { //propertyName就是alias,大写 BasicPropertyAccessor.BasicGetter getter = getGetterOrNull(theClass, propertyName); Class returnType = getter == null?null:getter.getReturnType(); Method[] methods = theClass.getDeclaredMethods(); Method potentialSetter = null; Method[] arr$ = methods; int len$ = methods.length; for(int i$ = 0; i$ < len$; ++i$) { Method method = arr$[i$]; String methodName = method.getName(); if(method.getParameterTypes().length == 1 && methodName.startsWith("set")) { String testStdMethod = Introspector.decapitalize(methodName.substring(3)); String testOldMethod = methodName.substring(3); // 都是dto的setter值,Id、Name、BookName if(testStdMethod.equals(propertyName) || testOldMethod.equals(propertyName)) { // 所以,此处if为false;method=null potentialSetter = method; if(returnType == null || method.getParameterTypes()[0].equals(returnType)) { return method; } } } } return potentialSetter; }
// 这是fluent-hibernate的源码 ;com.github.fluent.hibernate.internal.util.reflection.ReflectionUtils /** * Try to find a class getter method by a property name. Don‘t check parent classes or * interfaces. * * @param classToCheck * a class in which find a getter * @param propertyName * a property name * @return the getter method or null, if such getter is not exist */ public static Method getClassGetter(Class<?> classToCheck, String propertyName) { PropertyDescriptor[] descriptors = getPropertyDescriptors(classToCheck); for (PropertyDescriptor descriptor : descriptors) { if (isGetter(descriptor, propertyName)) { return descriptor.getReadMethod(); } } return null; } private static boolean isGetter(PropertyDescriptor descriptor, String propertyName) { Method method = descriptor.getReadMethod(); return method != null && method.getParameterTypes().length == 0 && descriptor.getName().equalsIgnoreCase(propertyName); //忽略大小写找到setter } private static PropertyDescriptor[] getPropertyDescriptors(Class<?> beanClass) { try { return Introspector.getBeanInfo(beanClass).getPropertyDescriptors(); } catch (IntrospectionException ex) { throw InternalUtils.toRuntimeException(ex); } }
我并没去完整认真的去看fluent-hibernate,可能是因为自己也是想通过找到setter的去解决 + 作者回答时候也是说主要就是怎么找到setter,把BookName当作BOOKNAME看待:
Using a custom result transformer
Another way to solve the problem — using a result transformer that ignores method names case (treat
getFirstName()
asgetFIRSTNAME()
). You can write your own or use FluentHibernateResultTransformer. You will not need to use quotes and aliases (if you have column names equal to DTO names)
ps: 其实想看认真看下的,本来我想的不用写多少代码量。但发现作者写了好多…
尚存疑问:
我记得我还看到的说法有说重写或扩展oralce的dialect的。记得之前公司的项目框架有重写oracle的dialect,貌似sql中的别名不会被转换成全大写。
具体不清楚,整天都是在写垃圾的业务实现代码,就知道叫加班,代码一点质量都没有,不好看懂、不好扩展、方法老旧,只是为了实现当前业务需求应付客户。搞的下班了没时间、也没经理去深入一些框架的东西,烦躁…><!
【Hibernate】hibernate原生sql利用transformers返回多表自定义类型对象
标签:property this org query class 垃圾 declared setter custom
原文地址:http://www.cnblogs.com/VergiLyn/p/6002466.html