Hibernate

Selecting certain fields in Hibernate Criteria using Projections

Selecting certain fields in Hibernate Criteria using Projections

This is not a great post but many people will face this issue and the solution is very simple for which many will spend hours of time to find it.

Issue faced by many are selecting certain fields of the table using hibernate criteria, converting array of Objects (Object[]) to respective custom class object, Even after converting the values for the fields will be set to default rather than actual values of the fields.

Take an example :

  Class Person {
    private Integer personid;
    private String personname;
    private String mobilenumber;
    private String permanentaddress;
    private String localaddress;

    public Integer getPersonid(){ }

    public void setPersonid(Integer personid){ }

    public String getPersonname(){ }

    public void setPersonname(String personname){ }

    //Other fields getter/Setter
    
  }

In this example assume that you wish to fetch only personid and personname using hibernate criteria

Fetching only selected fields using Hibernate Criteria







  List persons = null;
  Criteria criteria = sessionObject.createCriteria(Person.class);
		 criteria.setProjection(Projections.projectionList().add(Projections.property("personid")).add(Projections.property("personname")));

 criteria.setResultTransformer(Transformers.aliasToBean(Person.class));
 persons = criteria.list();

Issue : All fields are getting empty/default values after using hibernate projections

This issue is a very difficult to tackle, because hibernate doesn’t through any exception for this but it returns objects filled with default values of fields.

Solution: The solutions is really simple, just use an alias to each field in projections

//See alias personid and personname for both the fields
//Projections.property(“personid”),”personid”) and Projections.property(“personname”),”personname”)

 criteria.setProjection(Projections.projectionList().add(Projections.property("personid"),"personid").add( Projections.property("personname"),"personname"));

 

The above solution doesn’t work for One-To-Many relationship also when there is an aggregation, has-a relationship.

A Wrapper to fetch selected fields using hibernate Projections for One-To-Many relationship

Download the library given below and import it in your project, then define a Response Class like PersonResponse.java, which should be exact replica of Person.java , where it holds all details of a person fetched from database person table.

then just use the below code 

personCriteria.setResultTransformer(new AliasToBeanNestedResultTransformer(PersonResponse.class));

Source Code : AliasToBeanNestedResultTransformer

Thanks to : http://stackoverflow.com/a/25770708/526438

Java Jar files; Java Libraries; JSON lib;

Java Jar files and Uses

JAR:  aopalliance-repackaged-2.2.0.jar 

Usage: aop alliance will be internally used by

Note : Google Guice Core is a powerful library released by Google for dependency injection, this works with java 6 and above ( download )

JAR:  apache-mime4j-0.6.jar

Usage: apache mime will be used for mime message parsing. This jar internally used by 

  • commons-io
  • commons-logging
  • junit like testing libraries
  • log4j 

JAR : commons-io

Usage – commons io provides utility classes, stream implementations, file filters,file comparators, endian transformation classes

JAR : asm-3.3.jar

Usage : asm jar will be used to analyse the byte code and analyse the frameworks

Note: asm is used by certain code generation libraries like cglib

JAR : gson-2.3.jar 

Usage : gson used to convert java objects into json object. Can be used in struts and springs to convert java objects. ( Documentation )

 JAR : persistence-api-1.0.jar

 Usage : The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications

Dependencies :

  • Servlet-API
  • Javax.inject 

JAR : hk2-api-2.2.0.jar 

Usage : This is called hundred kilobyte kernal for glassfish server, It forma the core glassfish server architecture

 

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.cess.service.Employee.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=EmployeeServiceImpl)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) … 25 more

Solution – 

This issue is a strange issue in hibernate autowire for bean objects, the solution will be as follows but no technical description why so ? 🙂

@Autowired
@Qualifier("EmployeeServiceImpl")
EmployeeService employeeService;  //EmployeeService is an interface


			




Change the above @Qualifier as below 
@Qualifier("employeeServiceImpl")

Note : the only change is instead of capital E in EmployeeServiceImpl, it should be small 'e' employeeServiceImpl
If it is reverse case then do make it Capital .

Hibernate QueryException : could not resolve property:

Hibernate QueryException :  could not resolve property:

org.hibernate.QueryException: could not resolve property: DP of: com.cess.pojo.Customer
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:67)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:61)
at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1402)
at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:54)
at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1377)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:457)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumnsUsingProjection(CriteriaQueryTranslator.java:417)
at org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:68)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:357)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:113)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:91)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1577)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at com.cess.dao.impl.CusomerDaoImpl$1.execute(CustomerDaoImpl.java:77)
at com.cess.framework.TransactionWrapper.run(TransactionWrapper.java:41)
at com.cess.dao.impl.CustomerDaoImpl.getCustomers(CustomerDaoImpl.java:43)
at com.cess.service.impl.CustomerServiceImpl.getCustomers(customerServiceImpl.java:39)
at com.cess.controller.CustomerController.Customers(CustomerController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

			




Solution –
Instead of using nested paths directly in Criteria API (unlike HQL), create nested criteria instances and use aliases on each “entity.property”
Example –







Criteria criteria = sessionObject
.createCriteria(Customer.class, "C")
.createAlias("C.department", "D")
.createAlias("D.Section", "S")
.createAlias("S.SubSection", "SB")

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:179)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:145)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:107)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:87)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:150)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 22 more

Solution
If your controller class are as follows








			




@Controller("/userinfo")
public class UserController {
@RequestMapping(method=RequestMethod.POST)
 public String userInfo(@RequestBody User user){
 }
}

@Controller("/userproject") 
public class UserProjectController {

@RequestMapping(method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){
  }
}

//Then Use value Element of @RequestMapping as follows
@Controller
public class UserController {
 
 @RequestMapping(value = "/getuserinfo", method=RequestMethod.POST)
 
  public String userInfo(@RequestBody User user){

  }
}


@Controller
public class UserProjectController {
 //Note value in both controller requestMapping should be different
 
 @RequestMapping(value = "/getuserproject",method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){

  }
}