Is it necessary to use AnnotationConfiguration for Hibernate Configuration? - java

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.

Related

mapping migration : Hibernate 4 to Hibernate 5

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?

Hibernate Enum Set Error

I have a Role object which holds several permissions(which are ENUM).
But i keep getting this error.
Use of #OneToMany or #ManyToMany targeting an unmapped class: objects.Role.permissions[enums.AgentPermission]
What is the best way to represent.
Role Class:
#Entity
#Table(name="\"Role\"")
public class Role {
#Id
#GeneratedValue
private int id;
#ManyToOne
private Company company;
private String name;
#ManyToMany
private Set<AgentPermission> permissions;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
....
}
hibernate.cfg.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>
<!-- hibernate dialect -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
....
<mapping class="objects.Role" />
<mapping class="objects.Tag" />
....
</session-factory>
</hibernate-configuration>
Try #ElementCollection on your Set of permissions.

Hibernate table not found

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

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