How to connect postgresql in hibernate.cfg.xml - java

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.

Related

Getting: 'Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]' Exception when doing Hibernate CRUD project

I am doing a 'JAVA project' in Eclipse Enterprise Edition IDE. Hibernate CRUD project to create user (student) details in my MySQL database (hibernatestudent). Hibernate version is Hibernate ORM core version 5.6.9.Final. My MySQL version is 8.0.29. I have the same version connector jar file for JDBC added in the build path library. All other related jar files related to Hibernate have been added also. I have tried the suggested solutions from other such issues of users but none seems to solve my problem.
Below shows Exception when running StudentDAO.java file.
Exception
Jun 10, 2022 11:46:40 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.6.9.Final
Jun 10, 2022 11:46:40 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
POJO Class file
package com;
// POJO Class file (persistent class)
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 = "Student")
public class Student {
#Id // Primary key for this table.
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
private String firstName;
private String lastName;
private String email;
public int getId() { // Generating getters & setters.
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
StudentDAO.java file
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class StudentDao {
public static void main(String[] args) { // Main method
StudentDao.insert_data();
}
public static void insert_data() {
try {
// Hibernate API to save this objects to DB
//Session factory is created only ONCE
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
// create transaction
session.beginTransaction();
Student obj_Student = new Student(); // Sending the above collected values to this entity class to be stored in our database.
obj_Student.setFirstName("Student_One");
obj_Student.setId(987);
session.save(obj_Student);
session.getTransaction().commit();
//Closing the session
session.close();
sessionFactory.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
hibernate cfg xml 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">
<!-- Version 8 MySQL hibernate.cfg.xml for Hibernate 5 -->
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.datasource">jdbc/myDS</property>
<property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/hibernatestudent</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- Disable auto commit mode -->
<property name="hibernate.connection.autocommit">false</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">4</property>
<property name="current_session_context_class">thread</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Format SQL -->
<property name="format_sql">true</property>
<!-- Database tables are automatically created -->
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Names the annotated entity class-->
<mapping class ="com.Student"/>
</session-factory>
</hibernate-configuration>
jar files used are as below
jar files
verify your configuration properties, i got this error and it was due to a bad url.
you can refer to this question: https://stackoverflow.com/questions/36345377/unable-to-create-requested-service-org-hibernate-engine-jdbc-env-spi-jdbcenviro.

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 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 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