Hibernate table not found - java

Here is my entity
#Entity
public class User {
#Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And here is my hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/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>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- List of XML mapping files -->
<mapping class="User"/>
</session-factory>
</hibernate-configuration>
I have an empty database called test having user and password "root". But when I try to create a User and save it to database, I get an exception saying
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.user' doesn't exist
What have I done wrong?

It's because the test.user is not available in database.
Either you need to create the table before starting your application sever
(or)
Enable the hibernate DDL generation to true, to let the hibernate create the table if it does not exist. (Don't do it in production or QA environment, as it is not a good practice).
Add this to the hibernate properties list.
<property name="hibernate.hbm2ddl.auto">update</property>

Add below property in your configuration file.
<property name="hbm2ddl.auto">create</property>
Thanks

Related

Hibernate acessing table in schema other than dbo results with Schema-validation: missing table

I have a datasource that has two schemas: dbo and example.
I've created a table in dbo schema called A, and mapped it in hibernate:
#Entity
#Table(name = "A")
public class ATable {
private Integer id;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
It runs without any errors as expected, I then proceeded to move the table to example schema with the following statement (runs successfully):
alter schema example transfer dbo.A
And changed the hibernate class as well:
#Entity
#Table(name = "A", schema = "example")
public class ATable {
private Integer id;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
But upon running it, it throws the following exception, and exit the program.
INFO: HHH000262: Table not found: A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [A]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
at com.venditio.Application.main(Application.java:21)
I also tried using the following table annotation instead:
#Table(name = "example.A")
But it throws somewhat the same exception:
INFO: HHH000262: Table not found: example.A
Sep 22, 2017 3:53:36 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: example.A
Exception in thread "main" org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [example.A]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:130)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.performValidation(SchemaValidatorImpl.java:100)
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.doValidation(SchemaValidatorImpl.java:65)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:459)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:711)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:727)
at com.venditio.Application.main(Application.java:21)
It seems that I need to somehow configure hibernate to support the extra schema, but don't understand how.
Application:
public class Application {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
sessionFactory.openSession().close();
}
}
And hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--MSSQL-->
<property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/d1</property>
<property name="connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property>
<property name="hibernate.connection.username">a</property>
<property name="hibernate.connection.password">1</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<!--Global-->
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.a.A" />
</session-factory>
</hibernate-configuration>
Turns out, removing the following line from hibernate.cfg.xml did the trick
<property name="hibernate.hbm2ddl.auto">validate</property>

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.

Is it necessary to use AnnotationConfiguration for Hibernate Configuration?

I want to use Configuration() methot. But I get this error:
Initial SessionFactory creation failed.org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.example.domain.Lesson"/>
If I use AnnotationConfiguratin() method, Hibernate can read my classes. I don't understand this:
Why when I use Configuration method, Hibernate can't see <mapping class="com.example.Lesson"/> definition?
My hibernate.cfg.xml 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>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/DB</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<mapping resource="com.example/Lesson.hbm.xml" />
<mapping class="com.example.Lesson"/>
</session-factory>
</hibernate-configuration>
My Lesson class :
public class Lesson implements java.io.Serializable {
private int id;
private String lesson;
private Set lessons = new HashSet(0);
public Lesson() {
}
public Lesson(int id, String lesson, Set lessons) {
this.id = id;
this.id = id;
this.lessons = lessons;
}
continue..
}
I had bhm.xml files from reverse engineering. So, I don't want to use Annotation.
Any idea?
Just remove <mapping class="com.example.Lesson"/> from hibernate.cfg.xml. It is not necessary because Lesson.hbm.xml is present.

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