JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

JPA Vs Hibernate

December 29, 2013 by Krishna Srinivasan Leave a Comment

I have come across this question from many of our readers and who ever working on the hibernate framework : What is the difference between Java Persistence API (JPA) and Hibernate ORM Framework. This post simply answer to those who are confusing with JPA and Hibernate difference.

JPA and Hibernate Difference

JPA is a specification for accessing, persisting and managing the data between Java objects and the relational database. As the definition says its API, it is only the specification. There is no implementation for the API. JPA specifies the set of rules and guidelines for developing the interfaces that follows standard. Straight to the point : JPA is just guidelines to implement the Object Relational Mapping (ORM)  and there is no underlying code for the implementation.

Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation.

Hibernate is a JPA provider. When there is new changes to the specification, hibernate would release its updated implementation for the JPA specification. Other popular JPA providers are Eclipse Link (Reference Implementation), OpenJPA, etc. You can find the latest release of JPA providers.

In summary, JPA is not an implementation, it will not provide any concrete functionality to your application.  Its purpose is to provide a set of rules and guidelines that can be followed by JPA implementation vendors to create an ORM implementation in a standardized manner.  This allows the underlying JPA implementation to be swapped and for developers to easily transition (think knowledge wise) from one implementation to another.  Hibernate is the most popular JPA provider.

 

Filed Under: Hibernate, Java Tagged With: Hibernate 4 Tutorials, JPA 2 Tutorials

JPA 2 Criteria API

December 28, 2013 by Krishna Srinivasan Leave a Comment

One of the important feature in JPA 2.0 is using the Criteria API for forming the SQL queries. If you would have worked with the JPA 1.0 version, you must be familiar with the Java Persistence Query Language (JQL) which is similar to writing the SQL queries. This approach is good for the developers who are much familiar with SQL syntax and programming, for the Java developers who are not comfortable with SQL will leads to lot of syntax error. One of the dis-advantage with JQL is, it can not capture the grammar errors at the compile time. If you have errors at SQL, it is thrown errors at the run time. Criteria API solves this problem by providing he strongly typed metamodel objects (Read : Generate MetaModel Using Eclipse or Ant) for writing the queries.

For the beginners who are not familiar with the JPA concepts, please read our article on Introduction to JPA before start reading this tutorial.

JPA Criteria API vs JPQL

JPQL queries are defined as the SQL strings. The only difference with the normal SQL is that JPQL has its own grammar for querying the datbase. For simple static queries, using JPQL is preferred. It will be easy for you to write a query instead of forming it using the CriteriaBuilder. When you build query at run time, writing plain SQL query would have unnecessary string concatenation operations which will leads to lot of syntax issues which can not be detected at the compile time.

String based JPQL queries and JPA criteria based queries are equivalent in power and performance. Choosing one method over the other is also a matter of personal choice. If you choose for your  projects, please consider the pros and cons of each method. However, JPA itself recommends using the Criteria API.

Problem with JPQL Query

Lets look at the below code:

[code lang=”java”]
EntityManager em = …;
String jpql = "select e from Employee where e.id > 20";
Query query = em.createQuery(jpql);
List result = query.getResultList();
[/code]

If you look at the above code, it has one error. The correct code is below:

[code lang=”java”]
String jpql = "select e from Employee e where e.id > 20";
[/code]

These errors are caught at the run time. That is the main dis-advantage of using the JPQL query.

A Simple JPA Criteria Query

The following query represents a simple JPQL query:

[code]
select * from employee e
[/code]

The same query can be built using the JPA criteria API as below:

[code lang=”java”]
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> e = cb.createQuery(Employee.class);
Root<Employee> ee = e.from(Employee.class);
e.select(ee);
[/code]

CriteriaBuilder is the main factory for getting the criteria queries. You can get this object by using the EntityManagerFactory or EntityManager interface.

Typesafe Criteria Query with Metamodel

I have explained in the previous post about the metamodel. It helps you to understand the metamodel and requires understanding the below code.

[code lang=”java”]
EntityManager em = …
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = qb.createQuery(Employee.class);
Root<Employee> p = c.from(Employee.class);
Predicate condition = qb.gt(p.get(Employee_.id), 20);
c.where(condition);
TypedQuery<Employee> q = em.createQuery(c);
List<Employee> result = q.getResultList();
[/code]

The above code has many new things which is introduced from JPA 2. But, here we have to understand the TypedQuery which is the important concept for making the query is strongly typed.  Also look at the “Employee_” which is generated as part of the metamodel.

Reference Links

  • Dynamic, typesafe queries in JPA 2.0
  • JPA Query API
  • JPA 2.0 Features

Filed Under: Java EE Tagged With: Hibernate 4 Tutorials, JPA 2 Tutorials

How To Create EntityManagerFactory in JPA

December 28, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains how to create EntityManagerFactory in your JPA application when you are writing your first JPA programming. It is the standard way of creating the factory if you use the JPA specification. Normally there are two ways to create the factory, one is through the configuration file persistence.xml and another one is through the application server configurations. Here I am going to explain about the first approach how to writing in your programming. You have to follow these steps for creating your EntityManagerFactory.

  1. Create persistence.xml file under the classpath. Make sure that you keep this file under META-INF folder. For example, your source files are maintained in the folder “src”, then create a META-INF folder under “src”.
  2. Another important point is to add the persistence unit name in the configuration file. This one will be used while creating the EntityManagerFactory. Note that each factory will have a name. You can have multiple factories with multiple configuration files. If you are not specifying the unit name, you would get the  javax.persistence.PersistenceException: No Persistence provider for EntityManager named JPAUNIT
  3. Create the factory by passing the persistence unit name as the parameter.
  4. I assume that you have setup the project with all the required files for Java Persistence API (JPA).

Lets see the sample code:

persistence.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="JPAUNIT">
<provider>javax.persistence.spi.PersistenceProvider</provider>
<class>javabeat.net.hibernate.Employee</class>
<properties>
<property name="connection.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="connection.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="connection.jdbc.user" value="root"/>
<property name="connection.jdbc.password" value="admin"/>
</properties>
</persistence-unit>
</persistence>
[/code]

HibernateUtil.java

[code lang=”java”]
package javabeat.net.hibernate;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class HibernateUtil {
public static void main(String args[]){
EntityManagerFactory entityManager = Persistence.createEntityManagerFactory("JPAUNIT");
EntityManager entityManager2 = entityManager.createEntityManager();
EntityTransaction transaction = entityManager2.getTransaction();
transaction.begin();
Employee employee = new Employee();
employee.setEmpName("Senthil Kumar1");;
employee.setBranch("Pune");
entityManager2.persist(employee);
transaction.commit();
}
}
[/code]

Filed Under: Hibernate Tagged With: Hibernate 4 Tutorials, JPA 2 Tutorials

JPA EntityManagerFactory Vs Hibernate’s SessionFactory

December 28, 2013 by Krishna Srinivasan Leave a Comment

If you are using the JPA’s standard specification implementation (Read : Introduction to JPA), then you would use EntityManagerFactory for opening the session. But, if you are using the hibernate implementation, you have hibernate specific SessionFactory for managing the sessions. Here there is lot of confusion between developers like which one is the best approach. Here, there is two opinions are popular:

  1. EntityManagerFactory is  the standard implementation, it is the same across all the implementations. If we migrate our ORM for any other provider, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied  to hibernate APIs and ca not migrate to new vendor easily.
  2. One dis-advantage of using the standard implementation is that, it is not providing the advanced features. There is not much control provided in the EntityManager APIs. Whereas, hibernate’s SessionFactory has lot of advanced features which can not done in JPA. One such thing is retrieving the ID generator without closing the transaction, batch insert, etc.

Looking into the above points, one has to decide which one is better. There is no hard rule, after all it depends on the developers requirement. Another suggestion is that, we can use entity manger and session factory together. In this approach, entity manage delegates session handling to the hibernate by invoking the unwrap method. Like this:

[code lang=”java”]
Session session = entityManager.unwrap(Session.class);
[/code]

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts.

Filed Under: Hibernate Tagged With: Hibernate 4 Tutorials, JPA 2 Tutorials

JPA 2 MetaModel Generator using Ant

December 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained how to generate metamodel using your Eclipse IDE. However, in most scenarios you will have to create from your build scripts. This tutorial explains how to add this option in your ant script. For the detailed explanation on project example code, please refer the previous post. Here I explain only the build script.

Java Persistence API (JPA)

JPA 2 MetaModel Generator Using Ant Script

In the below script, compiler argument -proc:only, tells that only to process the meta annotated classes.

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="antan" name="Annotation">
<property environment="env" />
<property name="target" value="1.6" />
<property name="source" value="1.6" />
<property name="src.dir" value="${basedir}/src" />
<property name="target.dir" value="${basedir}/target" />
<property name="src.lib" location="${basedir}" />
<path id="classpath">
<fileset dir="${src.lib}">
<include name="*.jar" />
</fileset>
</path>
<target name="antan">
<javac srcdir="${src.dir}"
destdir="${target.dir}"
failonerror="false"
fork="true">
<compilerarg value="-proc:only"/>
<classpath refid="classpath" />
</javac>
</target>
</project>
[/code]

Project Structure

The files are generated to “target” folder in your project.

JPA MetaModel Ant

Hope this helps. You can just use the above script for generating the metamodel for your JPA projects.

Filed Under: Hibernate Tagged With: Apache Ant, Hibernate 4 Tutorials, JPA 2 Tutorials

JPA 2 MetaModel Generation using Eclipse

December 27, 2013 by Krishna Srinivasan Leave a Comment

JPA 2.0 introduces the strongly typed Criteria API for going away with the Java Persistence Query (JQL) language. It comes with the metamodel for helping the typed objects. Every entity must have a meta model generated with underscore(_) added to its name. These objects will be referred in the Criteria API instead of using the string based names. These files can be created manually. But, it will impact the productivity and consumes lot of effort for writing every file.

If you remember, Java 6.0 has nice feature known as annotation processing. This feature is utilized and JPA vendors have created the tools for generating metamodel by parsing the entity classes. It is fully automated once you run the tool. Here I am going to explain how you can use eclipse to generate the meta model class for you.

Create Eclipse Project and Classes

Create eclipse project for running this example tutorial for generating the metamodel classes. As a first step, create eclipse Java project and create the classes Employee.java, Device.java and Branch.java.

Employee.java

[code lang=”java”]
package javabeat.net.jpa;

import java.math.BigDecimal;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity public class Employee {
@Id
Integer id;
@ManyToOne
Branch branches;
@OneToMany
Set<Device> devices;
BigDecimal salary;
}
[/code]

Device.java

[code lang=”java”]
package javabeat.net.jpa;
public class Device {}
[/code]

Branch.java

[code lang=”java”]
package javabeat.net.jpa;
public class Branch {}
[/code]

Look at the below project structure how it looks.

JPA MetaModel Project Example

JAR files added are:

  • ibernate-jpamodelgen-4.3.0.Final.jar
  • javax.persistence_2.0.0.v200911271158.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar

Get JPA MetaModel Generator Tool

It is API provided by most of the JPA vendors for generating the meta data. Here I have used the hibernate-jpamodelgen-4.3.0.Final.jar, which is donwloaded from the hibernate project. Also you can get it from the example code for this tutorial at bottom.

Get JPA Implementation API

It is the actual JPA implementation. Note that, it can be specific for the ORM vendor. Every vendor has their own implementation for JPA. Here I have downloaded both, hibernate and official JPA implementation JAr files for this example tutorial.

Enable Annotation Processing In Your Eclipse Project

This feature is added from Eclipse 3.2 (Galilio). It is project level feature. You can right click on the project and click properties menu. You will get the following window. Enable the “project specific settings”, it will enable the annotation processing for that project. Also you can change source directory where the generated source code will be copied.

Select the “Factory Path” menu in the left side and add the meta model generator JAR file by selecting “Add External JAR”. After this change, when you click on OK, the project will built and the new folder would have created with the metamodel class. You can check in the above project folder structure for knowing where it will be generated.

JPA MetaModel Eclipse

JPA MetaModel Eclipse 2

Generated MetaModel Class

Once the above steps are completed, the below class will be generated.

Employee_.java

[code lang=”java”]
package javabeat.net.jpa;

import java.math.BigDecimal;
import javax.annotation.Generated;
import javax.persistence.metamodel.SetAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Employee.class)
public abstract class Employee_ {

public static volatile SingularAttribute<Employee, Integer> id;
public static volatile SingularAttribute<Employee, BigDecimal> salary;
public static volatile SetAttribute<Employee, Device> devices;
public static volatile SingularAttribute<Employee, Branch> branches;

}
[/code]

How to use these metamodel in Criteria API will be written in the next articles. Please stay tuned to get the more articles on JPA 2.

Download Source Code For This Example : JPAApp

Filed Under: Hibernate Tagged With: Eclipse Tips, Hibernate 4 Tutorials, JPA 2 Tutorials

Hibernate 4 Basic Configuration + Setup Example

December 25, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains the very basic configuration and installation of hibernate configuration for your project. It is a standalone program, but the same configuration would applicable for the web applications. Here I am using the XML configuration approach, I will write another tutorial for using the annotations. Here I assume that you have installed the MYSQL database required for this application.

1. Project Structure and Libraries

Look at the below screen shot for the sample project structure for the hibernate project. The file locations are as follows.

  • hibernate.cfg.xml – This is the main hibernate configuration file for loading the database configuration and mapping files for the entities. This must be the classpath location inside your project. By default hibernate would look for the root of the classpath directory. If you want to use the different location, you have to pass the location to the config object at the time of loading the configurations.
  • employee.hbm.xml – This is the mapping file for entity Employee in the database. This file will be different for each entity. Name of the file is <entity-name>.hbm.xml.
  • The following JAR files are required to start writing your first hibernate application. using MySQL database. These JAR files can be downloaded from the repository or add as the dependency in maven’s pom.xml.
    • classmate-1.0.0.jar
    • dom4j-1.6.1.jar
    • hibernate-commons-annotations-4.0.4.Final.jar
    • hibernate-core-4.3.0.Final.jar
    • hibernate-jpa-2.1-api-1.0.0.Final.jar
    • jandex-1.1.0.Final.jar
    • javassist-3.12.1.GA.jar
    • jboss-logging-3.1.4.GA.jar
    • jta-1.1.jar
    • mysql-connector-java-5.1.28.jar

Hibernate Project Structure

2. Maven Dependency

This section provides the list of dependency entry for the maven configuration. If I have missed any of the dependency here, please add it by searching from the maven repository.

[code lang=”xml”]
<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
</dependency>
<!– Hibernate framework –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0</version>
</dependency>
<!– Hibernate library dependecy start –>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
[/code]

3. MYSQL Database Table Creation

Create Table Employee

[code]
CREATE TABLE `employee` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`empname` VARCHAR(50) NULL DEFAULT NULL,
`branch` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`)
)
[/code]

Database credentials

[code]
Connection URL: jdbc:mysql://localhost:3306/test
DB Username: root
DB Password: <your mysql password>
[/code]

4. Entity Class

Lets see the entity class for persisting the object. It is a simple class defines the properties mapped to each column in the EMPLOYEE table.

Employee.java

[code lang=”java”]
package javabeat.net.hibernate;
public class Employee {
private int id;
private String empName;
private String branch;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}

}

[/code]

5. Hibernate Configuration File (hibernate.cfg.xml)

It is the main configuration file. Here you have to define the database details and mapping files locations. Here I have defined only the basic properties needed for an application, you can use lot many advanced properties like caching, etc. based on your requirement.

[code lang=”xml”]
<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
<!– Database connection settings –>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>

<!– JDBC connection pool (use the built-in) –>
<property name="connection.pool_size">1</property>

<!– SQL dialect –>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!– Echo all executed SQL to stdout –>
<property name="show_sql">true</property>

<!– Mapping files –>
<mapping resource="javabeat/net/hibernate/Employee.hbm.xml"/>
</session-factory>

</hibernate-configuration>
[/code]

6. Hibernate Mapping File (Employee.hbm.xml)

It is the per mapping configuration file. Normally this file will be placed along with the entity object. If you look at this file, it simply use the Employee class object and mapping the corresponding column names in the table. Few points to note:

  1. Package attribute used for defining the package path for the entity classes defined under that element.
  2. If column attribute is not defined, by default it takes the property name as the column name.  If your column name is different from the Java property name, then define it explicitly.
  3.  Id attribute is used for defining the primary key column in the table.

[code lang=”xml”]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="javabeat.net.hibernate">
<class name="Employee" table="employee">
<id name="id" column="id">
<generator class="increment"/>
</id>
<property name="empName" column="empname"/>
<property name="branch"/>
</class>
</hibernate-mapping>
[/code]

7. Run The Application

Once the above configurations are completed, lets write the util class to save some details to the database. This sample application stores values from the Employee object to the database.

[code lang=”java”]
package javabeat.net.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
public static void main(String args[]){
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Session session = factory.openSession();
Employee employee = new Employee();
employee.setEmpName("Senthil Kumar");;
employee.setBranch("Pune");
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
}
}
[/code]

Filed Under: Hibernate Tagged With: Hibernate 4 Tutorials

How To Create Session Factory in Hibernate 4

December 25, 2013 by Krishna Srinivasan Leave a Comment

There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:

[code lang=”java”]
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
[/code]

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:

[code lang=”java”]
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
[/code]

Class ServiceRegistryBuilder is  replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

Filed Under: Hibernate Tagged With: Deprecated, Hibernate 4 Tutorials

Deprecated @Entity Annotation in Hibernate 4

December 25, 2013 by Krishna Srinivasan Leave a Comment

In the earlier versions of Hibernate, we use @Entity for marking a class as persistence entity in the database. It has list of attributes to be used as the parameters. @Entity has been deprecated from the hibernate 4 and will be removed from the hibernate 5.0 release. There is a confusion in the consistency of  information provided on their websites about the removal of these annotations. However, If you are using this annotation in the earlier versions of hibernate, you have to change before planning to migrate your project to higher versions. @Entity has the following list of attributes.

  1. dynamicInsert
  2. dynamicUpdate
  3. mutable
  4. optimisticLock
  5. persister
  6. polymorphism
  7. selectBeforeUpdate

When @Entity is removed, each and every attribute listed above will have its own annotation definition as listed below:

  1. DynamicInsert
  2. DynamicUpdate
  3. Immutable
  4. OptimisticLocking
  5. Persister
  6. Polymorphism
  7. SelectBeforeUpdate

However, the annotation Entity is deprecated in favor of the JPA annotation @javax.persistence.Entity. If you would like to use it, you have to use the JPA one instead of the hibernate annotation. It is obvious that there will be lot of changes with the hibernate API in the future versions, I would suggest to use the latest version if you are starting a new project.

Filed Under: Java Tagged With: Deprecated, Hibernate 4 Tutorials

Hibernate Exception – javassist.util.proxy.MethodFilter

December 25, 2013 by Krishna Srinivasan Leave a Comment

If you are using Hibernate 4, you would hit this exception while setting up the first hibernate application. The missing library is javassist. To resolve this problem, either manually download the JAR file or add the below maven try to your project’s POM.xml. Once you added these library, the error will be fixed. This library is used for:

Javassist (Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level. If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. The whole API is designed with only the vocabulary of the Java language. You can even specify inserted bytecode in the form of source text; Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors.

[code lang=”xml”]
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
[/code]

Exception Trace

[code]
Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
at org.hibernate.bytecode.internal.javassist.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:58)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:244)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:222)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:212)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:80)
… 19 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
[/code]

Filed Under: Hibernate Tagged With: Hibernate 4 Tutorials

  • 1
  • 2
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved