Showing posts with label Troubleshoot. Show all posts
Showing posts with label Troubleshoot. Show all posts

Wednesday, 23 September 2015

The database returned no natively generated identity value; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value

Several reasons are there for this issue :


Why ?
IDENTITY ID generator with a table column which is not properly configured. It should be an auto_increment column for the IDENTITY generator to work. Else, the database doesn't return any generated ID.

How to solve?
1) And fixing this is as simple as making sure that the Primary Key Column, of the table you are working with, has Auto Increment set.

 2) In such scenario, you not need to create table manually. It will create by default using hibernate. make change or add in hibernate.cfg.xml >> "hibernate.hbm2ddl.auto" field set to "update".

3) We must auto_increment the id column of the table by using below query
   ALTER TABLE document MODIFY COLUMN document_id INT auto_increment

PLEASE COMMENT YOUR SOLUTION IF YOU FOUND BY OTHER WAY

Tuesday, 8 September 2015

Eclipse “Error: Could not find or load main class”

Some time eclipse not run any java file and give exception like
"Error: Could not find or load main class"

Bellow are few solution :

Solution 1 )
  • went to run configurations: - run->run configurations
      In the Classpath tab:
  • Select Advanced
  • Add where Eclipse usually put the *.class for the projects, which is in bin. So I added the bin directory for the project.
Solution 2)
   
  • Project -> Clean will remove any existing class files and completely rebuild the project.
Solution 3)

It seems that the class is not compiled by Eclipse.
Few pointers could be-
  1. Check if the .class file exists in your output folder.To know your output folder Right Click on Project->Properties->Java Build Path(Check at bottom).
  2. Check if Project->build Automatically is checked in the menu.
  3. Check if the HelloWorld class is in src folder or not.Right Click on Project->Properties->Java Build Path(Check source tab).

Monday, 3 August 2015

java.lang.UnsatisfiedLinkError: no dll in java.library.path

  1. Create a folder under the project, for example dll.
  2. Copy/paste all dll files into this folder.
  3. In project -> Properties -> Java Build Path -> Source, click and expand the source details.
  4. You will see Native library location, click/highlight it.
  5. Then click edit on the right, click workspace again. You can see the dll folder under the project.
  6. Select it and click OK, OK. You will see the dll is added in the Native library location.
That's it. You do not need to manually change anything in configuration.

Friday, 26 June 2015

Java Hibernate : hibernate-could-not-obtain-transaction-synchronized-session-for-current-thread

Some times with hibernate we got error while fetching data from database.

Error like :

hibernate-could-not-obtain-transaction-synchronized-session-for-current-thread

For this error one of the simple solution is :

Just user @Transactional annotation in your DAO implementation method from where you got error.

For Example :
        ...
        ...
        @Transactional
@Override
public List<Object> listObjectCategory(String objectName) {
...
....
}

Please put your valuable inputs and solutions to improving this post

Thursday, 18 June 2015

How to stop Tomcate server when it is not stop from eclipse

In some situation Apache Tomcat not stop from eclipse at that time we have to forcefully stop that server by using kill that process, Here we show this simple task that is very useful for developers.

This solution is tested and working file with Windows platform :

First of all we want to know that which process ID is for Apache tomcate port.

For that we follow bellow steps :
-> Open command promt  
-> Type command :
     netstat -o -n -a | findstr 8080
     Where 8080 is the PORT number on which Tomcat is start.
-> It will show you result like :
    TCP    0.0.0.0:8080                  0.0.0.0:0                       LISTENING         6852
    TCP    192.168.0.193:63473    192.168.0.100:8080     CLOSE_WAIT     6852
    TCP    [::]:8080                        [::]:0                             LISTENING         6852
    TCP    [::1]:8080                      [::1]:63536                   TIME_WAIT        0

-> Where the last number is ther Process ID that you have to kill for stooping the service on which Tomcat working. This number is differ every time.

-> For kill the process type the bellow command in command prompt :
    taskkill /F /PID 6852
    6852 is the process id that you get from first command.

-> This command will show you message like :
     SUCCESS: The process with PID 6852 has been terminated.

-> That it now you can restart Tomcat and it will start as normal way. Now enjoy the code.

KEEP VISITING THIS BLOG FOR MORE TECH DISCUSSION. 
YOUR SUGGESTION ARE WELCOMES FOR ANY POST.

Wednesday, 27 May 2015

Eclipse: Add the javax.servlet package to a project?

Some time in eclipse project we have exception in all the .java file where we use any servlet package this is because of we do not include servlet file in system jdk path.

To solve the error please follow bellow steps :

  1. Right click your project folder, select Properties at the bottom of the context menu.
  2. Select "Java Build Path"
  3. Click Libraries" tab
  4. Click "Add Library..." button on right (about halfway down)
  5. Select "Server Runtime" click "Next"
  6. Select your Tomcat version from the list
  7. Click Finish

KEEP READING FOR MORE POST

Thursday, 30 April 2015

How to resolve tomcat – java.lang.OutOfMemoryError: PermGen space

Often time, Tomcat may hits the following java.lang.OutOfMemoryError: PermGen space error.
java.lang.OutOfMemoryError: PermGen space
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
It’s usually happened after the Tomcat restarts a few times.

1. Solution

By default, Tomcat is assigned a very little PermGen memory for the running process. To fix it, increase the PermGen memory settings by using the following Java VM options.
In eclipse by default it is 256 MB. You can increase it by your need. If you are use eclipse then set this value in "eclipse.ini" initialization file.
-XX:PermSize<size> - Set initial PermGen Size.
-XX:MaxPermSize<size> - Set the maximum PermGen Size.
In the next step, we will show you how to set the VM options in Tomcat, under Windows and Linux environment.

2. Windows

Tomcat is managed by this script file catalina.bat, dive inside the script, you will find out thatcatalina.bat always find and run the setenv.bat file to set the environment variables.
{$tomcat-folder}\bin\catalina.bat
//...
rem Get standard environment variables
if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome
call "%CATALINA_BASE%\bin\setenv.bat"
goto setenvDone
:checkSetenvHome
if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"
:setenvDone
//...
2.1 To set the environment variable on Windows, create a setenv.bat manually, and put it into the${tomcat-folder}\bin folder.
${tomcat-folder}\bin\setenv.bat
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
P.S No double quotes, set JAVA_OPTS={value}.
2.2 Restart Tomcat, it will call the setenv.bat file to set the environment variable automatically.
{$tomcat-folder}\bin\catalina.bat restart

3. Linux

On Linux, the process is same, just Tomcat is using catalina.sh and setenv.sh instead.
3.1 Find out where is catalina.sh :
catalina.sh
$ sudo find / -name "catalina.sh"
Password:
find: /dev/fd/3: Not a directory
find: /dev/fd/4: Not a directory
/Users/mkyong/Downloads/apache-tomcat-6.0.35/bin/catalina.sh
3.2 Review the catalina.sh, script, it behaves like Windows, but use setenv.sh instead.
//...
# Ensure that any user defined CLASSPATH variables are not used on startup,
# but allow them to be specified in setenv.sh, in rare case when it is needed.
CLASSPATH=
 
if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then
  . "$CATALINA_BASE/bin/setenv.sh"
elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then
  . "$CATALINA_HOME/bin/setenv.sh"
fi
//...
3.3 Create a setenv.sh manually, and put it into the ${tomcat-folder}\bin\ folder.
${tomcat-folder}\bin\setenv.sh
export JAVA_OPTS="-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m"
P.S With double quotes, export JAVA_OPTS=”{value}”.
3.4 Restart Tomcat.
Note
The heap size and non-heap size (perm gen) value is just an example, you should change the value accordingly to suit your project needs.
* Original post on mkyong.com

Thursday, 12 March 2015

Hibernate Issue – Initial SessionFactory Creation Failed.Java.Lang.NoClassDefFoundError: Org/Dom4j/DocumentException

A common Hibernate’s error, this is caused by the missing dependency library – dom4j.
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/dom4j/DocumentException
Exception in thread "main" java.lang.ExceptionInInitializerError
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
 at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
 at com.mkyong.common.App.main(App.java:17)
Caused by: java.lang.NoClassDefFoundError: org/dom4j/DocumentException
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
 ... 2 more
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 3 more

Solution

You can download the library here – http://sourceforge.net/projects/dom4j/files/dom4j/
Or
Add the dependency in Maven’s pom.xml
       <dependency>
  <groupId>dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>1.6.1</version>
 </dependency>

Hibernate Issue – An AnnotationConfiguration Instance Is Required To Use

The Hibernate annotation is required “AnnotationConfiguration” instead of normal “Configuration()” to build the session factory.
INFO: Configuration resource: /hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.MappingException: 
An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/>
Exception in thread "main" java.lang.ExceptionInInitializerError
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
 at com.mkyong.persistence.HibernateUtil.<clinit>(HibernateUtil.java:8)
 at com.mkyong.common.App.main(App.java:11)
Caused by: org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.mkyong.common.Stock"/>
 at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1600)
 at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
 at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
 at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
 at com.mkyong.persistence.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
 ... 2 more

Solution

1. Download the Hibernate annotation library

You can download the library from Hibernate official website
Or
Add the dependency in Maven’s pom.xml
        <!-- Hibernate annotation -->
 <dependency>
  <groupId>hibernate-annotations</groupId>
  <artifactId>hibernate-annotations</artifactId>
  <version>3.3.0.GA</version>
 </dependency>
P.S You may need to include the JBoss repository in order to download the Hibernate annotation library.
<repositories>
    <repository>
      <id>JBoss repository</id>
      <url>http://repository.jboss.com/maven2/</url>
    </repository>
  </repositories>

2. Use AnnotationConfiguration to build session factory

Normal Hibernate XML file mapping is using Configuration()
          return new Configuration().configure().buildSessionFactory();
For Hibernate annotation, you have to change it to “AnnotationConfiguration”
          return new AnnotationConfiguration().configure().buildSessionFactory();
HibernateUtil.java
A full example of “HibernateUtil.java” of using “AnnotationConfiguration” for Hibernate annotation applacation.
package com.mkyong.persistence;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
 
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public static void shutdown() {
     // Close caches and connection pools
     getSessionFactory().close();
    }
 
}

Hibernate Issue - Org.Hibernate.AnnotationException: Unknown Id.Generator

Problem

Runing the following Hibernate’s annotation sequence generator with PostgreSQL database.
        @Id 
 @Column(name="user_id", nullable=false) 
 @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="account_user_id_seq")
 private Integer userId;
Hits the following Unknown Id.generator exception.
Caused by: org.hibernate.AnnotationException: Unknown Id.generator: account_user_id_seq
 at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
 at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
 at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
 at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
The sequence “account_user_id_seq” is created in PostgreSQL database, what caused the above exception?

Solution

When declaring the Hibernate’s annotation strategy to use “Sequences” as Id generator, try specify the @SequenceGenerator as well, as following
        @Id 
 @Column(name="user_id", nullable=false) 
 @SequenceGenerator(name="my_seq", sequenceName="account_user_id_seq")
 @GeneratedValue(strategy = GenerationType.SEQUENCE ,generator="my_seq")
 private Integer userId;

Hibernate Issue - Remember That Ordinal Parameters Are 1-Based!...

Problem

HibernateTemplate code …
getHibernateTemplate().find("from Domain d 
where d.domainName = :domainName", domainName);
When i execute the above code, i hit the following error message
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
 ...
 at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:397)
 at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:369)

Solution

I go inside and study HibernateTemplate.java file and find below code
public List find(final String queryString, final Object[] values) throws DataAccessException {
 return (List) executeWithNativeSession(new HibernateCallback() {
  public Object doInHibernate(Session session) throws HibernateException {
   Query queryObject = session.createQuery(queryString);
   prepareQuery(queryObject);
   if (values != null) {
    for (int i = 0; i < values.length; i++) {
     queryObject.setParameter(i, values[i]);
    }
   }
   return queryObject.list();
  }
 });
}
From code above, the HibernateTemplete is using 0-based instead of 1-based. Is this a spring or hibernate library problem? Since error message stated parameters need to start at 1-based. I tried some solution like change spring or hibernate library, however it’s not working…
It’s seem I’m on a wrong direction, i have to start finding solution at beginning again, first i study my own code…………!!! I cant imaging how careless i am, i made a stupid mistake on my code, this is not spring or hibernate problem, it is my syntax error.
Change from
getHibernateTemplate().find("
    from Domain d where d.domainName = :domainName", domainName);
To
getHibernateTemplate().find("
    from Domain d where d.domainName = ?", domainName);
Problem solved, code execute without error anymore.
Note
The error message generated by HibernateTemplate is really misleading !!!

Hibernate Issue - Java.Lang.ClassNotFoundException : Javassist.Util.Proxy.MethodFilter

Problem

Using Hibernate 3.6.3, but hits this javassist not found error, see below for error stacks :
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
 ...
 at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
 ... 16 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
 at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
 at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
 ... 21 more

Solution

javassist.jar is missing, and you can get the latest from JBoss Maven repositorty.
File : pom.xml
<project ...>
 <repositories>
  <repository>
   <id>JBoss repository</id>
   <url>http://repository.jboss.org/nexus/content/groups/public/</url>
  </repository>
 </repositories>
 
 <dependencies>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.3.Final</version>
  </dependency>
 
  <dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
  </dependency>
 
 </dependencies>
</project>

Hibernate Issue – The Type AnnotationConfiguration Is Deprecated

Problem

Working with Hibernate 3.6, noticed the previous “org.hibernate.cfg.AnnotationConfiguration“, is marked as “deprecated“.
Code snippets …
import org.hibernate.cfg.AnnotationConfiguration;
//...
private static SessionFactory buildSessionFactory() {
 try {
 
  return new AnnotationConfiguration().configure().buildSessionFactory();
 
 } catch (Throwable ex) {
 
  System.err.println("Initial SessionFactory creation failed." + ex);
  throw new ExceptionInInitializerError(ex);
 }
}
The code is still working, just keep displaying the deprecated warning message, is there any replacement for “AnnotationConfiguration” ?

Solution

In Hibernate 3.6, “org.hibernate.cfg.AnnotationConfiguration” is deprecated, and all its functionality has been moved to “org.hibernate.cfg.Configuration“.
So , you can safely replace your “AnnotationConfiguration” with “Configuration” class.
Code snippets …
import org.hibernate.cfg.Configuration;
//...
private static SessionFactory buildSessionFactory() {
 try {
 
  return new Configuration().configure().buildSessionFactory();
 
 } catch (Throwable ex) {
 
  System.err.println("Initial SessionFactory creation failed." + ex);
  throw new ExceptionInInitializerError(ex);
 }
}