Impavid Impavid - 1 month ago 10
MySQL Question

Java 1.8 Maven + Hibernate + MySQL Example (XML Mapping)

Please help fix the Error:

'java.lang.NoClassDefFoundError: org/hibernate/Session' ...
'A JNI error has occurred, please check your installation and try again
Exception in thread "main"'
[Error in both Git Bash and Eclipse-jee-neon-R-win32-x86_64]


My Environment:

$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

$ mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:47+05:30)
Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.3.9
Java version: 1.8.0_102, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_102\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 8.1", version: "6.3", arch: "amd64", family: "dos"


Here's the code snippet:

MySQL



DROP DATABASE IF EXISTS hibernatedb;
CREATE DATABASE hibernatedb;
USE hibernatedb;

DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
`STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`STOCK_CODE` VARCHAR(10) NOT NULL,
`STOCK_NAME` VARCHAR(20) NOT NULL,
PRIMARY KEY (`STOCK_ID`) USING BTREE,
UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


pom.xml



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample.common</groupId>
<artifactId>HibernateMavenMySQLXMLSample</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>HibernateMavenMySQLXMLSample</name>
<url>http://maven.apache.org</url>
<dependencies>

<!-- JUnit 4.12 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!-- Hibernate framework -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.3.ga</version>
</dependency>

<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>

<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- Hibernate library dependecy end -->

</dependencies>

</project>


src/main/resources/com/sample/common/Stock.hbm.xml



<?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.sample.common.Stock" table="stock" catalog="sample">
<id name="stockId" type="java.lang.Integer">
<column name="STOCK_ID" />
<generator class="identity" />
</id>
<property name="stockCode" type="string">
<column name="STOCK_CODE" length="10" not-null="true" unique="true" />
</property>
<property name="stockName" type="string">
<column name="STOCK_NAME" length="20" not-null="true" unique="true" />
</property>
</class>
</hibernate-mapping>


src/main/java/com/sample/common/Stock.java



package com.sample.common;

/**
* Model class for Stock
*/
public class Stock implements java.io.Serializable {

private static final long serialVersionUID = 1L;

private Integer stockId;
private String stockCode;
private String stockName;

public Stock() {
}

public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}

public Integer getStockId() {
return this.stockId;
}

public void setStockId(Integer stockId) {
this.stockId = stockId;
}

public String getStockCode() {
return this.stockCode;
}

public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}

public String getStockName() {
return this.stockName;
}

public void setStockName(String stockName) {
this.stockName = stockName;
}

}


src/main/resources/hibernate.cfg.xml



<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">***********</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/sample/common/Stock.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>


src/main/java/com/sample/persistence/HibernateUtil.java



package com.sample.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().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();
}

}

# src/main/java/com/sample/common/App.java

package com.sample.common;

import org.hibernate.Session;
import com.sample.persistence.HibernateUtil;

public class App
{
public static void main( String[] args )
{
System.out.println("Maven + Hibernate + MySQL");
Session session = HibernateUtil.getSessionFactory().openSession();

session.beginTransaction();
Stock stock = new Stock();

stock.setStockCode("4715");
stock.setStockName("GENM");

session.save(stock);
session.getTransaction().commit();
}
}


$ java -cp target/HibernateMavenMySQLXMLSample-1.0-SNAPSHOT.jar com.sample.common.App

java.lang.NoClassDefFoundError: org/hibernate/Session
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.hibernate.Session
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 7 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main"


What is wrong with the above code and configuration in spite of Build Success as follows:



$ mvn eclipse:eclipse
[INFO] Scanning for projects...

[INFO] Not writing settings - defaults suffice
[INFO] File E:\Working\Java\Hibernate\HibernateMavenMySQLXML\HibernateMavenMySQLXMLSample\.project already exists.
Additional settings will be preserved, run mvn eclipse:clean if you want old settings to be removed.
[INFO] Wrote Eclipse project for "HibernateMavenMySQLXMLSample" to E:\Working\Java\Hibernate\HibernateMavenMySQLXML\HibernateMavenMySQLXMLSample.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 05:30 min
[INFO] Finished at: 2016-11-04T01:07:24+05:30
[INFO] Final Memory: 13M/247M
[INFO] ------------------------------------------------------------------------

$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building HibernateMavenMySQLXMLSample 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ HibernateMavenMySQLXMLSample ---

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.sample.common.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.086 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ HibernateMavenMySQLXMLSample ---
Downloading: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.pom
Downloaded: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.pom (10 KB at 8.9 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.15.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.jar
Downloading: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-interpolation/1.15/plexus-interpolation-1.15.jar (60 KB at 45.6 KB/sec)
Downloading: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar (57 KB at 43.6 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar (37 KB at 26.6 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/commons-lang/commons-lang/2.1/commons-lang-2.1.jar (203 KB at 91.7 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0/plexus-utils-3.0.jar (221 KB at 87.6 KB/sec)
Downloaded: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-archiver/2.1/plexus-archiver-2.1.jar (181 KB at 51.5 KB/sec)
[INFO] Building jar: E:\Working\Java\Hibernate\HibernateMavenMySQLXML\HibernateMavenMySQLXMLSample\target\HibernateMavenMySQLXMLSample-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:52 min
[INFO] Finished at: 2016-11-04T01:09:28+05:30
[INFO] Final Memory: 19M/268M
[INFO] ------------------------------------------------------------------------


Thanks.

Answer

What you need here is to produce an executable jar. This jar should primarily contain three things viz.
1. Your classes.
2. The classes present inside the jars that you have added as dependency.
3. A manifest file that specifies your main class.

With the current pom.xml that you have, your artifact will only contain your classes. To add the other two things that I mentioned above, you can use the Maven Assembly Plugin.
Add the below piece of code within the <project></project> tag in your pom.xml.

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>com.sample.common.App</mainClass>
            </manifest>
          </archive>
        </configuration>
        <executions>
          <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>  

This will produce two jars in the target folder. One of it will have just your classes and the other jar will have all the things that I mentioned above. The second jar will have jar-with-dependencies appended to its name.
You should use this jar to run your application.