Friday, December 4, 2015

Microservices Architecture with exmaple

Microservices are a way to break down a monolithic application into small, simple and independent services that work together, where each is responsible fro a specific function. This brings scalability

The basic concept of microservices also talks about the

Features of MicroServices:
- Service Oriented Approach
- Componentization via Services
- Organized around business capabilities
- Products not projects
- Smart end point dump pipes
- Decentralized governance
- Decentralized data management
- Infrastructure automation
- Design for failure
- Evolutionary design

Tools for building Micro Services

- Scriptable cloud infrastructire to automate continuos delivery release pipelines
- Reliable Messaging Infrastructire to allow service chirography
- Highly productive development framework
- Containerless runtime to allow deployment of one executable per service

Spring Boot

- It makes it easy to create stand-alone, production-grade Spring based Applications.
- Embed Tomcat or Jetty Directly (no need to deploy WAR files)
- Automatically configure Spring whenever possible
- Provide production ready features such as metrics, health checks and externalized configuration.

Create a Spring Boot Application :

References :
This is an example to package and run a spring boot application as a microservice. It will bring up the spring application with an embedded web server.  The executable jar includes all the required libraries to run this as an independent service. Following are the details :

  • The code can be downloaded from github:
https://github.com/SanjayIngole/demo-microservice-springboot/archive/master.zip
  • There is runnable microservice jar as well that can be downloaded from following location:
https://github.com/SanjayIngole/demo-microservice-springboot/blob/master/DemoMicroServices/target/demo-0.0.1.jar

  • To run this microservic. It will bring up the spring application with an embedded web server. 
java -jar demo.jar
  • A test page can be used to upload the sample xml and obtain JSON response.
https://github.com/SanjayIngole/demo-microservice-springboot/blob/master/DemoMicroServices/src/main/resources/testpage.html
  • You can use a docker or boxfuse to deploy this on cloud. I use boxfuse to deploy my microservices to aws. You can setup a boxfuse account (https://console.boxfuse.com/) and configure your aws instance, and then download boxfuse command line client.

  • Package your project using maven, which will package all dependent jars in one file.
    • mvn package
  • And then deploy it using boxfuse command, this deploy this application on configured aws instance. 
    • boxfuse run demo:0.0.1


Tuesday, December 1, 2015

aws mysql connection issues

I just set up a new spring mvc + hibernate application on aws instance via elastic beanstalk.
I created a new MySql db and was able to access it through my localhost, but I couldn't connect to mysql through my beanstalk application deployed on aws instance. 

I was able to fix these issues, and thought its worth sharing the solution as many others developers might be facing the same issue.  The connectivity issue could happen for different reasons, but in my 
case it was security groups that caused the issue.

First thing to make sure you correctly created you db instance, try to ping it from console.

>>>  nc -zv test.xxxxxxxxx.us-west-2.rds.amazonaws.com 3306
Connection to mgdb.czivgxrqpb9q.us-west-2.rds.amazonaws.com port 3306 [tcp/mysql] succeeded!

The aws troubleshooting guide is helpful and I would recommend to read it first.
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Troubleshooting.html#CHAP_Troubleshooting.Connecting

Here is my spring-hibernate configuration file just for the reference:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="appDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://xxxxxxx.us-west1.rds.amazonaws.com:3306/mgdb?zeroDateTimeBehavior=convertToNull"/>
    <property name="username" value="xxxxxx"/>
    <property name="password" value="xxxxxx"/>
</bean>

<bean id="appSessionFactory" 
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="appDataSource"/>
    <property name="mappingResources">
        <list>
            <value>employee.hbm.xml</value>        
        </list>
    </property>
    <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
    </property>
</bean>

<bean id="hibernateTemplate" 
class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory">
        <ref bean="appSessionFactory"/>
    </property>
</bean>

</beans>

  • First Connectivity issue:

28-Nov-2015 23:58:47.504 ERROR [localhost-startStop-1] <unknown>.<unknown> Unable obtain JDBC Connection
 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection refused

Fix:

Initially I was getting Connection refused exception but this was gone once I updated the security group to enable all traffic to my ElasticBeanstalk application. 

I have updated the security group to accept All traffic with default IP as shown here. 
(This is okay for testing if you are troubleshooting the connectivity issue, but its a good idea to set specific protocols and destination for more security)


  • Second Connectivity issue :

org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Caused by: java.net.ConnectException: Connection timed out

Fix :
After resolving first issue I was still getting Connection timed out error. Going further in aws documentation I found that we also need to enable the DB Security group to make it accessible from EC2. 

As per aws docs - A DB security group controls network access to a DB instance that is not inside a VPC. By default, network access is turned off to a DB instance. You can specify rules in a security group that allows access from an IP address range, port, or EC2 security group. 

More can be found at this link:
http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithSecurityGroups.html

To change this, go to you DB instance and select "See Details" from "Instance Actions" dropdown.
On the details page click on the security group for your db instance.

Check the inbound and outbound settings for your DB security group. For testing purpose I am setting it to accept All traffic but its always recommended to configure more specific protocols and ip addresses, specially if its production database.

Inbound:


Outbound:





Tuesday, October 20, 2015

No converter found for return value of type: class java.util.ArrayList

I am testing a Spring MVC application , I am calling a database service which returns an ArrayList. I want to return this ArrayList as a Json response to my Jsp, where I am going to iterate through it and render search results through jquery.

 @RequestMapping(value = "/web/getprofiles", method = RequestMethod.GET)
    public @ResponseBody
    List getProfiles(HttpServletRequest request) {
        ArrayList<SearchDO> searchResults = profileService.getProfileSearch();
     return searchResults;

    }

Getting following exception while returning the ArrayList from Controller method :

Oct 20, 2015 10:45:20 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/web] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList] with root cause
java.lang.IllegalArgumentException: No converter found for return value of type: class java.util.ArrayList
at org.springframework.util.Assert.isTrue(Assert.java:68)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:124)

I am running this application on tomcat 7.0 with jdk 1.8 and Spring version 4.2.1.RELEASE.

Fix:

The exception here indicates that spring can not find a suitable converter to return ArrayList as a Json object as expected. To resolve this configure the resource resolver in your spring configuration xml.
Make you have specified <annotation-driven /> in spring configuration.



Spring configuration xml

          

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<context:component-scan base-package="com.testweb.controllers" />

<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <beans:property name="useNotAcceptableStatusCode"
        value="false" />
    <beans:property name="contentNegotiationManager">
        <beans:bean
            class="org.springframework.web.accept.ContentNegotiationManager">
            <beans:constructor-arg>
                <beans:bean
                    class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                    <beans:constructor-arg>
                        <beans:map>
                            <beans:entry key="html" value="text/html" />
                            <beans:entry key="json" value="application/json" />
                        </beans:map>
                    </beans:constructor-arg>
                </beans:bean>
            </beans:constructor-arg>
        </beans:bean>
    </beans:property>

    <beans:property name="viewResolvers">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
            
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean id="jspView"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <beans:property name="prefix" value="/WEB-INF/views/" />
                <beans:property name="suffix" value=".jsp" />
            </beans:bean>
        </beans:list>
    </beans:property>

    <beans:property name="defaultViews">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
        </beans:list>
    </beans:property>
</beans:bean>

</beans:beans>


             



Make sure you have added required jackson dependencies in your pom.xml

<!-- Jackson JSON Mapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.2</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.5.2</version>

</dependency>

Monday, October 19, 2015

Caused by: java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V

Getting following exception while trying to build a hibernate Spring web application on tomcat.

Following is the Exception :

Caused by: java.lang.NoSuchMethodError: org.jboss.logging.Logger.debugf(Ljava/lang/String;I)V
at org.hibernate.internal.NamedQueryRepository.checkNamedQueries(NamedQueryRepository.java:149)
at org.hibernate.internal.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:764)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:495)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)

... 21 more

Solution:

Checked for the dependency hierarchy in pom.xml


Added the exclusion to hibernate-entitymanager dependency:

<dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
            <exclusions>           
                <exclusion>
                    <artifactId>jboss-logging</artifactId>
                    <groupId>org.jboss.logging</groupId>
                </exclusion>
            </exclusions>

         </dependency>


You might get following after adding exclusion :

Caused by: java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2944)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1208)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1688)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:28)
at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:24)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:86)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 21 more
Caused by: java.lang.ClassNotFoundException: org.jboss.logging.BasicLogger
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
... 34 more

ERROR: org.springframework.web.context.ContextLoader - Context initialization failed


Try adding the following dependency in pom :

<dependency>
           <artifactId>jboss-logging</artifactId>
           <groupId>org.jboss.logging</groupId>            
           <version>3.2.0.Final</version>
</dependency>

ERROR: org.hibernate.internal.SessionFactoryImpl - HHH000302: Unable to construct current session context [org.springframework.orm.hibernate4.SpringSessionContext]

Getting following exception while trying to start up a spring hibernate application :

ERROR: org.hibernate.internal.SessionFactoryImpl - HHH000302: Unable to construct current session context [org.springframework.orm.hibernate4.SpringSessionContext]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.hibernate.internal.SessionFactoryImpl.buildCurrentSessionContext(SessionFactoryImpl.java:1229)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:491)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:189)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:350)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:335)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4973)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
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.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/service/jta/platform/spi/JtaPlatform
at org.springframework.orm.hibernate4.SpringSessionContext.<init>(SpringSessionContext.java:56)
... 35 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569)
... 36 more

INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 9698 ms

Tuesday, October 6, 2015

java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider

I just upgraded a Hibernate Spring Application from 3.6.10 to Hibernate 5.0.0.Final.
Getting following exception during startup.


Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:/Users/workspace/testapp/src/main/resources/spring-hibernate.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:532)
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:589)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:33)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/cache/CacheProvider
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:53)
at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:44)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:239)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:155)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:323)
at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:353)
at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:429)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1132)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.CacheProvider
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

... 25 more

java.lang.UnsupportedOperationException: org.hibernate.dialect.HSQLDialect does not support resultsets via stored procedures

I have a Hibernate Spring Application. Following is my stored procedure mapping in config file profile.hbm.xml

 <!-- search_profiles  -->
 <sql-query name="searchProfiles" callable="true" >
 <return class="com.testapp.service.dataobjects.ProfileDO">
 </return>
  {  call get_search_results(:profileId, :loginId, :firstName, :lastName, :addressLine1, :addressLine2, :addressLine3, :city, :state, :zipCode, :country) }
 </sql-query>

I am trying to invoke this procedure as follows from my Java code :


List<ProfileResultObject> profilesResultSet = hibernateTemplate.findByNamedQueryAndValueBean("getSearchResults", searchCriteria);

Getting following exception while calling this stored procedure from Java :

java.lang.UnsupportedOperationException: org.hibernate.dialect.HSQLDialect does not support resultsets via stored procedures
at org.hibernate.dialect.Dialect.registerResultSetOutParameter(Dialect.java:1262)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1713)
at org.hibernate.loader.Loader.doQuery(Loader.java:801)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2542)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:316)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1842)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:157)
at org.springframework.orm.hibernate3.HibernateTemplate$35.doInHibernate(HibernateTemplate.java:1028)
at org.springframework.orm.hibernate3.HibernateTemplate$35.doInHibernate(HibernateTemplate.java:1023)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByNamedQueryAndValueBean(HibernateTemplate.java:1023)

Monday, October 5, 2015

org.hibernate.MappingException: composite-id class must implement Serializable

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:/Users/workspace/test_service/src/main/resources/spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: composite-id class must implement Serializable: com.test.service.geolocation.GeoLocationData
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:589)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:33)
Caused by: org.hibernate.MappingException: composite-id class must implement Serializable: com.test.service.geolocation.GeoLocationData
at org.hibernate.mapping.RootClass.checkCompositeIdentifier(RootClass.java:263)
at org.hibernate.mapping.RootClass.validate(RootClass.java:244)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1362)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1865)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:863)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:782)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)

... 12 more

Sunday, October 4, 2015

Hibernate UnsupportedOperationException: The user must supply a JDBC

xception in thread "main" java.lang.UnsupportedOperationException: The user must supply a JDBC connection
    at org.hibernate.connection.UserSuppliedConnectionProvider.getConnection(UserSuppliedConnectionProvider.java:54)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
    at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1700)
    at org.hibernate.loader.Loader.doQuery(Loader.java:801)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
    at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3294)
    at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
    at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
    at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
    at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
    at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
    at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
    at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005)
    at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998)
    at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:519)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
    at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:512)
    at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:506)
    at com.testapp.service.profiles.ProfileDao.getProfile(ProfileDao.java:49)
    at org.test.service.SpringHibernateTest.main(SpringHibernateTest.java:41)

org.hibernate.AnnotationException: No identifier specified for entity

Getting following exception while running a test Spring Hibernate Application :

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:/Users/workspace/testapp/src/main/resources/spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.testapp.service.profiles.Profile
    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:589)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:31)
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.testapp.service.profiles.Profile
    at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:268)
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:223)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:686)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:4035)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3989)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1398)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:720)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
    ... 12 more

Saturday, October 3, 2015

Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity

Getting following exception while running a test Spring Hibernate Application :

Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.testapp.service.profiles.MGProfile; nested exception is org.hibernate.MappingException: Unknown entity: com. testapp.service.profiles.MGProfile
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:690)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:512)
at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:506)
at com. testapp.service.profiles.MGProfileDao.getMGProfile(MGProfileDao.java:49)
at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:41)
Caused by: org.hibernate.MappingException: Unknown entity: com. testapp.service.profiles.MGProfile
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:92)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998)
at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:519)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)

... 5 more

HibernateException: 'hibernate.dialect' must be set

Getting following exception while running a test Spring Hibernate Application :


INFO - Building new Hibernate SessionFactory
INFO - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4cb2c100: defining beans [mgDataSource,mySessionFactory,hibernateTemplate,mgProfileDao,geoLocationDataDao]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:/Users/workspace-amazon/testapp/src/main/resources/spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available
    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:589)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:31)
Caused by: org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available
    at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.java:106)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:152)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2863)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:863)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:782)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:188)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
    ... 12 more


Fix :
There could be others fixes as well as suggested in other posts, in my case it was following missing configuration in Session Factory:

 <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>

    </property>


I added the above to SessionFatcory config in spring context file:

<bean id="mySessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="annotatedClasses">
        <list>
            <value>com.testapp.service.geolocation.GeoLocationData</value>
            <value>com. testapp.service.profiles.MGProfile</value>
        </list>
    </property>    
     <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
    </property>
 </bean>

Above I am using MySql You can change the dialect as used by your application:

Postgres: org.hibernate.dialect.PostgreSQL82Dialect
Oracle: org.hibernate.dialect.Oracle10gDialect

Wednesday, September 30, 2015

Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException:

Getting following exception while testing an Hibernate Application.

I have GeoLocationDataDao while testing a method getGeoLocationFromZipCode(zipcode) which returns the coordinates for a provided zip code.

I get following exception while running the test class.
Exception in thread "main" org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.testapp.service.geolocation.GeoLocationData; nested exception is org.hibernate.MappingException: Unknown entity: com.testapp.service.geolocation.GeoLocationData at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:690) at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:512) at org.springframework.orm.hibernate3.HibernateTemplate.get(HibernateTemplate.java:506) at com.testapp.service.geolocation.GeoLocationDataDao.getGeoLocationFromZipCode(GeoLocationDataDao.java:35) at org.mg.service.SpringHibernateTest.main(SpringHibernateTest.java:46) Caused by: org.hibernate.MappingException: Unknown entity: com.mg.service.geolocation.GeoLocationData at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:92) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005) at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998) at org.springframework.orm.hibernate3.HibernateTemplate$1.doInHibernate(HibernateTemplate.java:519) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) ... 5 more


Fix :

Error was coming as the Entity object required by Dao could not be instantiated as it could not find its mapping.We have to list our classes in the session factory configuration. We can either have our entities auto-discovered using AnnotationSessionFactoryBean or we can use LocalSessionFactoryBean if have entity xml files.

Following is an example, if we are using EntityManager and annotations.

 <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="annotatedClasses">
        <list>
            <value>com.testapp.service.geolocation.GeoLocationData</value>
        </list>
    </property>
    ....
 </bean>


If we are not using annotation and want to specify the entities in a child xml we can use LocalSessionFactoryBean where we can specify a list of entity beans xmls as shown below.

<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="mgDataSource"/>
    <property name="mappingResources">
        <list>
            <value>geolocationdata.hbm.xml</value>      
            <value>profile.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
    </property>
</bean>

Here is a sample entity xml geolocationdata.hbm.xml configured above.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.testapp.service.geolocation.GeoLocationData" table="GeoLocationData">
    <id name="zip_code" column="zip_code">
        <generator class="assigned"/>
    </id>
  <property name="lat"><column name="lat"/></property>
  <property name="lon"><column name="lon"/></property>
  <property name="city"><column name="city"/></property>
  <property name="state_prefix"><column name="state_prefix"/></property>
  <property name="county"><column name="county"/></property>
</class>
</hibernate-mapping>