i want to create and add to database user with enum
but cannot create instance
Required type:javax.management.relation.Role
Provided: cinema.entity.Role
how to fix it
user class
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String login;
private String password;
#Enumerated(EnumType.STRING)
#Column(name = "role")
private Role role;
}
enum
public enum Role {
USER, MANAGER, ADMIN
}
db
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost:5432/cinema</property>
<property name="connection.username">user</property>
<property name="connection.password">user</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="cinema.entity.User"/>
<mapping class="cinema.entity.Film"/>
<mapping class="cinema.entity.Ticket"/>
<mapping class="cinema.entity.Role"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
trying to run
public class Runner {
public static void main(String[] args) {
Configuration configuration = new Configuration();
// либо в cfg прописать
// configuration.addAnnotatedClass(User.class);
// configuration.addAnnotatedClass(Ticket.class);
// configuration.addAnnotatedClass(Film.class);
configuration.configure();
try (SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession()) {
session.beginTransaction(); // начало
User user = User.builder()
.login("ivan#gmal.com")
.password("pass")
// Required type:javax.management.relation.Role
// Provided: cinema.entity.Role
.role(Role.USER) //got an error
.build();
session.save(user);
session.getTransaction().commit();//конец
}
}
}
i want to create and add to database user with enum
but cannot create instance
Required type:javax.management.relation.Role
Provided: cinema.entity.Role
how to fix it
Related
Can u help me? Idk what Im doing wrong...
//Employee.class
package org.example.entity;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#Entity
#Setter
#Getter
#AllArgsConstructor
#NoArgsConstructor
public class Employee {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "id", nullable = false)
private Integer id;
#Basic
#Column(name = "name", nullable = true, length = 10)
private String name;
#Basic
#Column(name = "surname", nullable = true, length = 15)
private String surname;
#Basic
#Column(name = "office_id", nullable = true)
private Integer officeId;
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.username">postgres</property>
<property name="connection.password">vfr4vgy7</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping class="org.example.entity.Employee"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
main
package org.example;
import org.example.entity.Employee;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Employee employee = new Employee();
employee.setName("New");
employee.setSurname("Hero");
employee.setOfficeId(1);
employee.setId(12);
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
session.close();
HibernateUtil.close();
}
}
HibernateUtil.class
package org.example;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
/**
* Created by Ариорх on 27.05.2017.
*/
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void close(){
getSessionFactory().close();
}
}
So, when I start the project Im catching (Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate persister: org.example.entity.Employee
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.getEntityDescriptor(MappingMetamodelImpl.java:416)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1492)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:197)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:182)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:28)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:78)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:649)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:641)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:636)
at org.example.Main.main(Main.java:16).
Using PostgresSQL. IntellIJ Ultimate version. Maybe problem in HibernateUtil.class?
To load the configuration from the hibernate.cfg.xml you have to call configure() on the StandardServiceRegistryBuilder:
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
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?
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 {
}
}
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.
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.