Hibernate updating from different sessions - java

I am porting a java fat client from JDBC SQLite to Hibernate H2.
Until now I tried to separate all my database code in separate classes, like
TableTeam or TableMember, which have methods like .getAllTeams() or .updateTeam(Team t). These methods acted as a wrapper around their sql queries they executed.
Now with hibernate I tried to leave the interface as good as possible and just change the SQL queries to hibernate functions, which mostly works.
With one exception: updating elements.
team = new Team(-1, "Team Name", Collections.<Member>emptySet());
#Test
public void testUpdateTeam() throws Exception {
table.addTeam(team);
team.setName("New Name");
table.updateTeam(team);
Team f = table.getAllTeams().get(0);
Assert.assertEquals(team, f);
}
results in the following exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ch.tiim.sco.database.model.Team.members, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:576)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:215)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:156)
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:160)
at java.util.AbstractSet.equals(AbstractSet.java:92)
at org.hibernate.collection.internal.PersistentSet.equals(PersistentSet.java:441)
at ch.tiim.sco.database.model.Team.equals(Team.java:81)
at org.junit.Assert.isEquals(Assert.java:131)
at org.junit.Assert.equalsRegardingNull(Assert.java:127)
at org.junit.Assert.assertEquals(Assert.java:111)
at org.junit.Assert.assertEquals(Assert.java:144)
at ch.tiim.sco.database.TableMemberTest.testEditTeam(TableMemberTest.java:45)
The code for .updateTeam(Team t) is the following:
public void updateTeam(Team t) {
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
s.update(t);
s.getTransaction().commit();
}
And the same for .addTeam(Team t) but s.save(t) instead of s.update(t)
And Team looks like this:
#Entity
#Table(name = "team")
public class Team implements Model {
#Id
#GeneratedValue
#Column(name = "team_id")
private int id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "club_id")
private Club club;
#ManyToMany
#JoinTable(name = "team_members",
joinColumns = {#JoinColumn(name = "team_id")},
inverseJoinColumns = {#JoinColumn(name = "member_id")}
)
private java.util.Set<Member> members;
//I stripped the constructor and the setters/getters
}
Now how do I get rid of this error, without guaranteeing that every call to hibernate is from the same thread?
Edit Here is the hibernate configuration
<?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">org.h2.Driver</property>
<!--property name="connection.url">jdbc:h2:./test</property-->
<property name="connection.username">user</property>
<property name="connection.password">pass</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</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.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">create</property>
</session-factory>
</hibernate-configuration>

For Junit testcases you need to bind an opened Session to the current Thread.
SessionFactory sf = null;
Session s = null;
SessionHolder holder = null;
#Override
protected void onSetUp() throws Exception {
System.out.println("On SetUP----");
sf = (SessionFactory) beanFactory.getBean("sessionFactory");
s = sf.openSession();
TransactionSynchronizationManager.bindResource(sf, new SessionHolder(s));
}
#Override
protected void onTearDown() throws Exception {
System.out.println("On onTearDown----");
// unbind and close the session.
holder = (SessionHolder)TransactionSynchronizationManager.getResource(sf);
s = holder.getSession();
s.flush();
TransactionSynchronizationManager.unbindResource(sf);
SessionFactoryUtils.releaseSession(s, sf);
// teardown code here
}
If you want to no more care about LazyInitialisationException read this, its well explain what happens, and how to resolve the problem definitely

Can you post your hibernate.cfg? I suspect? you don't have a configured session context:
E.g
thread

Related

Hibernate AnnotationException Thrown when SessionFactory is Created

I am having a problem with hibernate. I am updating a previously created database created in Oracle SQL in order to get some practice with hibernate. The thing is that I am getting an AnnotationException that one class object is trying to reference something from the other class. Here is the error:
org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.revature.bank.POJO.BankAccount.customer references an unknown entity: com.revature.bank.POJO.Customer
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:107)
at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1580)
at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1503)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1419)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
at com.revature.bank.POJO.DataFuncImp.createCustomer(DataFuncImp.java:16)
at com.revature.bank.POJO.Main.main(Main.java:9)
So, this is pointing to the line:
SessionFactory sf = new Configuration().configure().buildSessionFactory();
I have read that it might be happening because the annotations but none of the previously asked questions here seemed to work.
Here are my two classes: (i will only put the variables as that's where the error points to):
Customer.java
#Entity
#Table(name="USER_TABLE")
public class Customer {
#Id
#GeneratedValue
private int user_id;
#Column
private String user_fname;
#Column
private String user_lname;
#Column
private String user_email;
#Column
private String user_address;
#Column
private String user_city;
#Column
private String user_state;
#Column
private long cell_num;
#OneToMany(cascade= {CascadeType.ALL}, mappedBy="customer")
#JoinColumn(name="user_id")
private List<BankAccount> bacct;
BankAccount.java
#Entity
#Table(name="USER_ACCOUNT")
public class BankAccount {
#Id
#GeneratedValue
private long acct_id;
#Column
private double balance;
#ManyToOne
#JoinColumn(name="user_id")
private Customer customer;
And here is my hibernate config file as well(edited out the database connection info):
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">adminone</property>
<property name="hibernate.connection.password">adminpass</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle11gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> -->
<!-- <mapping resource="students.hbm.xml"></mapping> -->
<mapping class="com.revature.bank.POJO.Customer"></mapping>
<mapping class="com.revature.bank.POJO.BankAccount"></mapping>
</session-factory>
</hibernate-configuration>
I am using hibernate 3.0. Like i mentioned earlier, i have been trying to figure out the error but none of the online help seemed to fix it. As you can see, I'm not even trying to do anything to the database yet and it is throwing that exception. Any idea on why is this happening? Thank you in advance!!
You shouldn't have JoinColumn on both sides. Just on the owner side, so remove it from the Customer class.
Customer.java:
#OneToMany(cascade= {CascadeType.ALL}, mappedBy="customer")
private List<BankAccount> bacct;
BankAccount.java:
#ManyToOne
#JoinColumn(name="user_id")
private Customer customer;

Tomcat + hibernate = no persistent classes found for query class

I'm developing a web app and deploying it on Tomcat 7.0. My app uses a MySQL database. I've already configured connection between app and database and wanted to add Hibernate 5.2.5 support. I can communicate with database via Hibernate console with configuration below, and it works when I use it in non-web app. The problem is only when I deploy it on server. I get warning
no persistent classes found for query class: from entities.UserH
and then 500 server error caused by it.
My entity class:
#Entity
#Table(name = "users", uniqueConstraints = {#UniqueConstraint(columnNames = {"id"})})
public class UserH {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column(name = "login", nullable = false, length = 45)
private String login;
#Column(name = "name", nullable = false, length = 45)
private String name;
#Column(name = "surname", nullable = false, length = 45)
private String surname;
/* getters and setters*/
}
My hibernate-annotation.cfg.xml:
<?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>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/web-database</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Mapping with model class containing annotations -->
<mapping class="entities.UserH"/>
</session-factory>
</hibernate-configuration>
Method that should get users:
public List<UserH> getAllUsers() {
try (Session session = HibernateUtils.getSessionAnnotationFactory().getCurrentSession()) {
session.beginTransaction();
Query<UserH> usersQuery = session.createQuery("from entities.UserH", UserH.class);
List<UserH> usersList = usersQuery.getResultList();
session.getTransaction().commit();
return usersList;
}
}
As I mentioned - it works ok with normal app, but not with Tomcat. I added all available elements to web artifacts, but it didn't help. I even tried to add JPA support with persistance.xml, but still with no luck.
What else could be the problem?
edit: My HibernateUtils class:
public class HibernateUtils {
private static SessionFactory sessionAnnotationFactory;
private static SessionFactory buildSessionAnnotationFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null)
sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
}
Maybe this is not a proper answer fot my question, but this is what actually worked for me. I replaced hibernate with JPA configuration + hibernate.
So instead of using hibernate-annotation.cfg.xml + Session I used persistance.xml + EntityManager:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>entities.UserH</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/web-database"/>
<property name="javax.persistence.jdbc.user" value="Admin"/>
<property name="javax.persistence.jdbc.password" value="password2#"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
getEntityManager:
public static EntityManager getEntityManager() {
EntityManager entityManager = Persistence
.createEntityManagerFactory("NewPersistenceUnit")
.createEntityManager();
return entityManager;
}
getAllUsers:
public List<UserH> getAllUsers() {
EntityManager entityManager = HibernateUtils.getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
TypedQuery<UserH> usersQuery = entityManager.createQuery("from UserH ", UserH.class);
List<UserH> usersList = usersQuery.getResultList();
transaction.commit();
entityManager.close();
return usersList;
}
However, I still don't understand why this configurations works while hibernate alone didn't. Any comments/suggestions would be appreciated.
You should just change your query to reference only the class name:
session.createQuery( "FROM UserH", UserH.class )
The only time the package is important would be when you're defining entities as inner classes.
For those cases, you'd need to use the full class name, com.c.SomeOutterClass$MyEntity. Another alternative is to change the #Entity annotation so that it includes the name attribute so you explicitly name your entity class:
public class SomeOutterClass {
#Entity(name = "MyEntity")
public static class MyEntity {
}
}

Hibernate + MySQL simple batch insert extremely slow

I'm inserting 2500 records from Hibernate into a totally empty MySQL table. The insert is taking 5 minutes!
I've googled for hours and tried a few things like an autogenerated primary key but nothing seems to improve the performance.
An earlier version of my program was doing inserts concurrently (1 per thread with ~100 threads) and that was taking ~2 minutes. I thought batching should improve performance by ~10x but it seems to have backfired.
I'm using Google Cloud's MySQL with a db-f1-micro instance
This is what my table looks like (only table in the DB!):
CREATE TABLE `categories` (
`browse_node` varchar(60) NOT NULL,
`name` varchar(60) DEFAULT NULL,
`path` varchar(400) DEFAULT NULL,
`url` varchar(200) NOT NULL,
`level` int(11) NOT NULL,
PRIMARY KEY (`browse_node`)
)
This is the POJO:
package example.com;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Represents a category from the categories table
*/
#Entity
#Table(name = "categories")
public class Category {
#Id
#Column(name = "browse_node")
private String browseNode;
#Column(name = "name")
private String name;
#Column(name = "path")
private String path;
#Column(name = "url")
private String url;
#Column(name = "level")
private int level;
public Category() {
}
public Category(String browseNode, String name, String path, String url, int level) {
this.browseNode = browseNode;
this.name = name;
this.path = path;
this.url = url;
this.level = level;
}
// Omitting setters/getters
}
Here's the code doing the insertion:
private static void writeCategoriesToDb(Map<String, Category> categories) {
StatelessSession session = sessionFactory.openStatelessSession();
// Session session = sessionFactory.openSession();
session.beginTransaction();
int i = 0;
int batchSize = 50;
for (Category category : categories.values()) {
session.insert(category);
// if (i % batchSize == 0) {
// session.flush();
// session.clear();
// }
// i++;
}
session.getTransaction().commit();
session.close();
}
And here's the config file:
<?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://someIp/myDB</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="connection.useSSL">false</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">20</property>
<property name="hibernate.jdbc.batch_size">3000</property>
<property name="hibernate.id.new_generator_mappings">false</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="example.com.Category"/>
</session-factory>
</hibernate-configuration>
Found the answer here.
Adding rewriteBatchedStatements=true to my JDBC url fixed it!
It now takes ~2.2 seconds to insert all the records.
<property name="connection.url">jdbc:mysql://someIp/myDB?rewriteBatchedStatements=true</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 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