Per the documentation in section 14.6 in hibernate docs:
http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#queryhql-select
Quote:
Code:
select new Family(mother, mate, offspr)
from DomesticCat as mother
join mother.mate as mate
left join mother.kittens as offspr
assuming that the class Family has an appropriate constructor.
Why does the constructor in this case has to public?
This method in ReflectHelper gets called:
Code:
public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException {
final Constructor[] candidates = clazz.getConstructors();
for ( int i=0; i<candidates.length; i++ ) {
final Constructor constructor = candidates[i];
final Class[] params = constructor.getParameterTypes();
if ( params.length==types.length ) {
boolean found = true;
for ( int j=0; j<params.length; j++ ) {
final boolean ok = params[j].isAssignableFrom( types[j].getReturnedClass() ) || (
types[j] instanceof PrimitiveType &&
params[j] == ( (PrimitiveType) types[j] ).getPrimitiveClass()
);
if (!ok) {
found = false;
break;
}
}
if (found) {
if ( !isPublic(clazz, constructor) ) constructor.setAccessible(true);
return constructor;
}
}
}
throw new PropertyNotFoundException( "no appropriate constructor in class: " + clazz.getName() );
}
Notice the use of clazz.getConstructors() which only returns an array of public constructors - and then later when a constructor is found, a check is done to see if the consturctor is public or not???
Why not use clazz.getDeclaredConstructors() which would return constructors declared with any access level (public,protected, package and private) -
This same logic is used when searching for a default constructor for a mapped class, why not use it in this case?
I am trying to keep my domain model clean and I don't want to create unnecessary public constructors -
Any suggestions?
Thanks,
-Mujahid