mapping migration : Hibernate 4 to Hibernate 5 - java

I had an application working fine with Hibernate 4.
Maven dependency :
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
Entity :
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.util.Set;
#Entity
#Table(name = "USERS")
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Generated(GenerationTime.INSERT)
#Column(name = "ID")
private int userId;
#Column(name = "USERNAME")
private String userName;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
...
Hibernate configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/MY_USERS</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.archive.autodetection">class, hbm</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.jdbc.batch_size">20</property>
<mapping class="com.mk.hibernate.demo.User"/>
<mapping class="com.mk.hibernate.demo.Book"/>
</session-factory>
</hibernate-configuration>
Query :
public List<User> getUsers(){
Session session = sessionFactory.openSession();
List<User> users = session.createQuery(" from User").list();
session.close();
return users;
}
It works fine. However when I upgrade the hibernate version
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.13.Final</version>
</dependency>
And no further changes, I start getting the following exception :
org.hibernate.hql.internal.ast.QuerySyntaxException: User is not
mapped
What is the possible cause for this?

Related

Hibernate 5 PropertyAccessException: Error accessing field by reflection for persistent property

I'm using hibernate to save an object to the db (mysql) but I keep getting an this error which doesn't really make sense to me since I have getters and setters from #Data (also tried with the vanilla way, the same error)
org.hibernate.property.access.spi.PropertyAccessException:
Error accessing field [private java.lang.String com.corona.models.User.email]
by reflection for persistent property [com.corona.models.User#email] :
User{id=0, email='asd#asd.asd', password='$2a$10$6lZ9wdyT.EyNXO5iIxfeeu9gX9hk8WAlwyykxQ9qIeZmyb3nKK4K6'}
at com.corona.dao.UserDao.saveEmployee(UserDao.java:18)
at com.corona.auth.AuthApplication.register(AuthApplication.java:28)
Caused by: java.lang.IllegalArgumentException: Can not set
java.lang.String field com.corona.models.User.email to com.corona.models.User
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
The model:
package com.corona.models;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "USERS")
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "identity")
#Column(name = "id")
private int id;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
Config:
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/coronaTime?useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">*******</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>
<mapping class="com.corona.models.User" />
</session-factory>
</hibernate-configuration>
Save method:
public class UserDao {
private HibernateTemplate template;
public void saveEmployee(User u){
Transaction tx = null;
try {
var session= HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
session.save(u);
tx.commit();
} catch (Exception e) {
if( tx!=null) {
tx.rollback();
}
e.printStackTrace();
}
}
}
You need to have constructors for saving hibernate object.
Please add the following annotations:
#AllArgsConstructor(access = AccessLevel.PACKAGE)
#NoArgsConstructor(access = AccessLevel.PACKAGE)
(access as per your requirements)
Read this for explanation:
Why does Hibernate require no argument constructor?

Hibernate Table doesn't exist error

I really need your help.
I'm new t hibernate. Trying to save an object but all the time i'm getting error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.person' doesn't exist
Here is domain object:
#Table(name = "Person")
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
#Column(name = "Person_age")
private int age;
#Column(name = "Person_name")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is my hibernate config file:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">******</property>
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Show all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Mapping files -->
<mapping class="ua.macko.domain.Person" />
</session-factory>
</hibernate-configuration>
The error i am getting is: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernate.person' doesn't exist.
I was trying to set hbm2ddl.auto parameter to create and to update but that gave me no result.
Please tell me what am i doing wrong?
Thnx in advance
After adding javassist library the issue has been solved. Thanks to all for help!
<property name="hbm2ddl.auto">create</property>
Is wrong for hibernate.cfg.xml, use
<property name="hibernate.hbm2ddl.auto">create</property>
instead.

How to connect postgresql in hibernate.cfg.xml

I am trying to insert some data into postgresql through hibernate. However, there are not much tutorial about configurate hibernate with postgresql (I know, it should be similar to mysql =))
src/main/resources/hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://127.0.0.1:5432/myDatabase</property>
<property name="connection.username">myUser</property>
<property name="connection.password">myPassword</property>
<!-- JDBC connection pool (use the build-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- thread is the short name for org.hibernate.context.ThreadLocalSessionContext -->
<property name="current_session_context_class">thread</property>
<!-- Set "true" to show SQL statements -->
<property name="hibernate.show_sql">true</property>
<!-- mapping class using annotation -->
<mapping class="com.hib.entities.Student"></mapping>
</session-factory>
</hibernate-configuration>
src/main/java/
package com.hib.init;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Hibernateutil {
private static final SessionFactory sessionF;
private static final ServiceRegistry serviceR;
static {
Configuration conf = new Configuration();
conf.configure();
System.out.println("Begin");
serviceR = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
System.out.println("Ready???");
try {
sessionF = conf.buildSessionFactory(serviceR);
System.out.println("Success??");
}catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSeeionFactory() {
return sessionF;
}
}
src/main/java
package com.hib.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Student {
#Id
#GeneratedValue
private Integer id;
private String firstName;
private Integer age;
public Student() {}
public Student(Integer id, String firstName, Integer age) {
super();
this.id = id;
this.firstName = firstName;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
src/main/java
package com.hib.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hib.entities.Student;
import com.hib.init.Hibernateutil;
public class DemoFirst {
public static void main(String[] args) {
SessionFactory sessionFactory = Hibernateutil.getSeeionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Student student = new Student();
student.setFirstName("Bob");
student.setAge(26);
session.save(student);
session.getTransaction().commit();
session.close();
}
}
And this is the error I got :
Success??
Hibernate: select nextval ('hibernate_sequence')
Aug 12, 2014 11:01:10 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 42P01
Aug 12, 2014 11:01:10 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ERROR: relation "hibernate_sequence" does not exist
Position: 17
Exception in thread "main" org.hibernate.exception.SQLGrammarException: ERROR: relation "hibernate_sequence" does not exist
Position: 17
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy9.executeQuery(Unknown Source)
at org.hibernate.id.SequenceGenerator.generateHolder(SequenceGenerator.java:123)
at org.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:116)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:642)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:635)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:631)
at com.hib.demo.DemoFirst.main(DemoFirst.java:20)
Caused by: org.postgresql.util.PSQLException: ERROR: relation "hibernate_sequence" does not exist
Position: 17
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2062)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1795)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:479)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:367)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:271)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 14 more
pom.xml
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>8.4-701.jdbc4</version>
</dependency>
According to this thread you must set your Id annotation as follows:
#GeneratedValue(strategy = GenerationType.IDENTITY)
You forgot to add the DDL auto generation property. You can use any of the following settings:
<property name="hibernate.hbm2ddl.auto" value="update">
<property name="hibernate.hbm2ddl.auto" value="create">
<property name="hibernate.hbm2ddl.auto" value="create-drop">
update is going to create and then simply update the DDL schema
create is going to create the schema if it doesn't exist
create-drop will create the schema when the SessionFactory is initialized and destroy it when the SessionFactory is destroyed. This is useful during integration testing.
You should make mapping beetwen table-entity class, column- field. For example (table and columns should exist) :
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "first_name")
private String firstName;
#Column(name = "age")
private Integer age;
Because you are using #GeneratedValue()
It will look for how the database that you are using generates ids. For MySql or HSQSL, there are increment fields that automatically increment. In Postgres or Oracle, they use sequence tables. Since you didn't specify a sequence table name, it will look for a sequence table named hibernate_sequence and use it for default. So you probably don't have such a sequence table in your database and now you get that error.
Either add a hibernate_sequence
like
#GeneratedValue(strategy=SEQUENCE)
or
your own sequence table and use the annotations to name your sequence table that you have like
#GeneratedValue(strategy=SEQUENCE, generator="student_id_seq")
Hope that helps
Connect to Postgresql by Hibernate -> configuration in hibernate.cfg.xml would be :
<session-factory>
<!-- SQL dialect -->
<!-- <property name="dialect">org.hibernate.dialect.H2Dialect</property> -->
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/db_name</property>
<property name="connection.username">username</property>
<property name="connection.password">db_assword</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- <property name="hbm2ddl.auto">validate</property> -->
<!-- The mapping information of entities -->
<!-- <mapping class="hibernate_example.envers.Book" /> -->
<!-- <mapping class="hibernate_example.envers.Student" /> -->
<!-- <mapping class="hibernate_example.envers.AuditEntity" /> -->
</session-factory>
Your id should look like:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_id_gen")
#SequenceGenerator(name = "my_id_gen", sequenceName = "my_id_seq")
private Long id;
The sequenceName property should refer to the proper sequence in your database. If you created the column as sequence type, then it should be tableName_columnName_seq.

Unable to load class declared as < mapping class="Package.Class" /> in the configuration

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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/UsoSurvey</property>
<property name="hibernate.connection.username">UsoSurvey</property>
<property name="hibernate.connection.password">UsoSurvey</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">10</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.timeout">100</property> <!-- seconds -->
<mapping class="Modelo.Grpusuario"/>
<mapping class="Modelo.Menu"/>
<mapping class="Modelo.Encuesta"/>
...
In iReport
Tools->Options->iReport->Classpath
C:\Users\Administrador\Documents\NetBeansProjects\UsoSurvey\src\java\Util -> I*n this folder is the mapping class*
C:\Users\Administrador\Documents\NetBeansProjects\UsoSurvey\src\java\Modelo -> In this folder are the model classes
Grpusuario.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Modelo;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author Administrador
*/
#Entity
#Table(name = "grpusuarios", catalog = "UsoSurvey", schema = "")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Grpusuario.findAll", query = "SELECT g FROM Grpusuario g"),
#NamedQuery(name = "Grpusuario.findByGrupo", query = "SELECT g FROM Grpusuario g WHERE g.grupo = :grupo"),
#NamedQuery(name = "Grpusuario.findByDescripcion", query = "SELECT g FROM Grpusuario g WHERE g.descripcion = :descripcion")})
public class Grpusuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "grupo")
private Integer grupo;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 64)
#Column(name = "descripcion")
private String descripcion;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "secLevel")
private Collection<Menu> menuCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "grupo", orphanRemoval = true)
private Collection<Usuario> usuarioCollection;
public Grpusuario() {
}
....
but when trying to create the connection I get the following error: unable to load class declared as < mapping class="Modelo.Grpusuario" /> in the configuration

how to connect to MySql with Hbernate using Eclipse

I'm new to the hibernate and eclipse. I successfully did it with Derby by watching a youtube video. Now I want to do it with MySql.
I was successful to connect MySQL to eclips
Next i wrote simple persistant class person
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Person {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Next I wrote a test class for that
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class PersonTest {
/**
* #param args
*/
public static void main(String[] args) {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(Person.class);
cfg.configure("hibernate.cfg.xml");
new SchemaExport(cfg).create(true, true);
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
Person person = new Person();
person.setName("Alex");
person.setId(1);
session.save(cfg);
session.getTransaction().commit();
}
}
My Hibernate configuration file
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ruwaKuppi</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hibernate.default_schema">ruwaKuppi</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My Mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Person" table="PERSON">
<id name="id" type="int" column="ID" >
<generator class="assigned"/>
</id>
<property name="name">
<column name="NAME" />
</property>
</class>
</hibernate-mapping>
Now I'm getting this error....
![enter image description here][2]
13:13:17,795 INFO Version:15 - Hibernate Annotations 3.4.0.GA
13:13:17,818 INFO Environment:560 - Hibernate 3.3.2.GA
13:13:17,821 INFO Environment:593 - hibernate.properties not found
13:13:17,825 INFO Environment:771 - Bytecode provider name : javassist
13:13:17,830 INFO Environment:652 - using JDK 1.4 java.sql.Timestamp handling
13:13:17,927 INFO Version:14 - Hibernate Commons Annotations 3.1.0.GA
13:13:17,949 INFO Configuration:1474 - configuring from resource: hibernate.cfg.xml
13:13:17,950 INFO Configuration:1451 - Configuration resource: hibernate.cfg.xml
13:13:18,059 INFO Configuration:600 - Reading mappings from resource : person.hbm.xml
13:13:18,147 INFO Configuration:1589 - Configured SessionFactory: null
13:13:18,173 INFO Dialect:175 - Using dialect: org.hibernate.dialect.MySQLDialect
13:13:18,307 INFO HbmBinder:322 - Mapping class: Person -> PERSON
13:13:18,326 INFO AnnotationBinder:419 - Binding entity from annotated class: Person
13:13:18,364 INFO Mappings:161 - duplicate import: Person->Person
13:13:18,367 INFO EntityBinder:422 - Bind entity Person on table Person
Exception in thread "main" org.hibernate.DuplicateMappingException: Duplicate class/entity mapping Person
at org.hibernate.cfg.Mappings.addClass(Mappings.java:141)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:789)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:546)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:291)
at org.hibernate.cfg.Configuration.generateDropSchemaScript(Configuration.java:803)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:128)
at org.hibernate.tool.hbm2ddl.SchemaExport.(SchemaExport.java:91)
at PersonTest.main(PersonTest.java:18)
Please can any one help me to get out from this mess... Thank you very much for your concern..
p.s :I know that last code is not clear....I think this is the important line of above
13:13:18,367 INFO EntityBinder:422 - Bind entity Person on table Person
Exception in thread "main" org.hibernate.DuplicateMappingException: Duplicate class/entity mapping Person
at org.hibernate.cfg.Mappings.addClass(Mappings.java:141)
You tell Hibernate to load the mapping from the hibernate.cfg.xml file:
cfg.configure("hibernate.cfg.xml");
But you also tell it to add the Person class as a mapped-trough annotations entity:
cfg.addAnnotatedClass(Person.class);
Decide if you want to map the Person entity using annotations or using XML. If you choose XML, then remove the cfg.addAnnotatedClass(Person.class); line. If you choose annotations, then remove the <class name="Person" table="PERSON"> (and all its sub-elements of course) from the XML file.
person class file
#Entity public class Person {
private String name;
#Id
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
test class
public class PersonTest {
/**
* #param args
*/
public static void main(String[] args) {
Person person = new Person();
person.setName("Alex");
person.setId(1);
SessionFactory factory = Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
}
}
hibernate.cfg.xml
<!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/ruwaKuppi</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</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>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="Put your package name and class name here"/>
</session-factory>
</hibernate-configuration>
no need to add mapping file
make sure your hibernate jars are included with jdbc jar.
include jar from lib-bytecode-javassist,
jpa and required.
check hibernate.cfg.xml file,itshould include in src folder
Remove annotation '#id' from getter of id of Person class

Categories

Resources