I am trying to add Hibernate 5 as ORM for a backend to connect with a MySQL-database. I read many examples and tutorials but I always get an InvocationTargetException.
Here are the relevant code. Hope someone can help me.
hibernate.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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cooking</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="de.fani.cooking.object.User"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package de.fani.cooking.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory()
{
try
{
// Create session factory from cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex)
{
System.err.println("Initial session factory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
if (sessionFactory == null)
{
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
User.java
package de.fani.cooking.object;
import javax.persistence.*;
#Entity (name = "User")
#Table(name="User", uniqueConstraints={#UniqueConstraint(columnNames = {"id"})})
public class User
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column (name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column (name = "username", nullable = false, length = 30)
private String username;
#Column (name = "password", nullable = false, length = 256)
private String password;
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public User()
{
}
}
SQL
CREATE TABLE `User` (
`id` int(11) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
UserResource.java
package de.fani.cooking.resource;
import de.fani.cooking.hibernate.HibernateUtil;
import de.fani.cooking.object.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/user")
public class UserResource
{
#POST
#Path("register")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response register(User _user)
{
User test = new User();
test.setId(24);
test.setUsername("tester");
test.setPassword("secret");
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(test);
session.getTransaction().commit();
session.flush();
return Response.status(Response.Status.OK).entity(_user).build();
}
}
Exception at session.save(test);:
SCHWERWIEGEND: Servlet.service() for servlet [ApplicationConfig] in context with path [] threw exception [org.hibernate.MappingException: Unknown entity: de.fani.cooking.object.User] with root cause
org.hibernate.MappingException: Unknown entity: de.fani.cooking.object.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1462)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338)
at com.sun.proxy.$Proxy58.save(Unknown Source)
Thanks a lot!
Ok, I found the answer by myself. The problem was the way I initialized the configuration, if I understand it correctly.
I changed it to:
private static SessionFactory buildSessionFactory()
{
try
{
// Create session factory from cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml")
.build();
Metadata Meta = new MetadataSources(serviceRegistry)
.addAnnotatedClass(User.class)
.addAnnotatedClassName("de.fani.cooking.model.User")
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
SessionFactory sessionFactory = Meta.getSessionFactoryBuilder()
.build();
return sessionFactory;
}
catch (Throwable ex)
{
System.err.println("Initial session factory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
And now it works! :-)
Related
Apologies for asking this when other people have asked before, but the other solutions appear to use #ComponentScan which is for Spring, and I am using dropwizard, so that wont work for me.
This is my (pretty simple) DTO class.
package apidto.entity.organization;
import lombok.Data;
import javax.persistence.*;
#Entity
#Table(name = "organization")
#NamedQueries({#NamedQuery( name =
"apidto.entity.organization.Organization.findAll",
query = "SELECT o from Organization o")})
public #Data class Organization {
#Id
private long id;
#Column(name = "name")
private String name;
}
and I have the following DAO class...
import apidto.entity.organization.Organization;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import java.util.List;
public class OrganizationDAO extends AbstractDAO<Organization> {
public OrganizationDAO(SessionFactory sessionFactory)
{
super(sessionFactory);
}
public List<Organization> findAll()
{
return list(namedQuery("apidto.entity.organization.Organization.findAll"));
}
}
You should use ScanningHibernateBundle in the Application class. ScanningHibernateBundle will scan apidto.entitypackage and all nested packages and add all classes with #Entity annotation to the Hibernate SessionFactory.
class SomeApp extends Application<SomeConfiguration> {
#Override
public void initialize(Bootstrap<SomeConfiguration> bootstrap) {
HibernateBundle<SomeConfiguration> hibernate = new ScanningHibernateBundle<SomeConfiguration>(
"apidto.entity") {
#Override
public PooledDataSourceFactory getDataSourceFactory(SomeConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
bootstrap.addBundle(hibernate);
}
}
I had the same problem using Dropwizard and Hibernate. I had a User entity class like this:
#Entity
#Table(name = "users")
#NamedQueries({
#NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findAll",
query = "SELECT u FROM User u"),
#NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword",
query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String username;
private String password;
/*private List<Bookmark> bookmarks = new ArrayList<>();*/
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
...
And then I had my DAO class as:
public class UserDAO extends AbstractDAO<User> {
UserDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
List findAll() {
return list(namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findAll"));
}
public Optional<User> findByUsernamePassword(String username, String password) {
return Optional.ofNullable(uniqueResult(
namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword")
.setParameter("username", username)
.setParameter("password", password)
));
}
}
Then here is how my hibernate.cfg.xml looked:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1</property>
<property name="connection.username">sa</property><!--./target/example-->
<property name="connection.password">sa</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Enable Hibernate's current sessions tracking by thread of execution -->
<property name="current_session_context_class">managed</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>
<mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>
</session-factory>
</hibernate-configuration>
I thought that the mapping tag in the hibernate.cfg.xml should be enough to do the mapping of User:
<mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>
but Apparently, it was not. So What I had to do was to add the following extra line to the class in which I am building the SessionFactory using the hibernate configuration (in my case HibernateUtil):
configuration.addAnnotatedClass(User.class);
So eventually here is how my HibernateUtil looked like after the fix:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(User.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
This question already has answers here:
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
(6 answers)
Closed 5 years ago.
I am creating a simple application using Hibernate JPA (annotations) and MySQL.I keep getting a:
WARN: HHH000183: no persistent classes found for query class: from
tn.ensi.cloudtrustproject.dao.entity.Country
when testing the Hibernate mapping.
I could not locate the problem so far. Please any help.
This is my 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>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name=
"hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name=
"hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/TrustCloud</property>
<property name="hibernate.connection.pool_size">1</property>
<property name=
"hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider
</property>
<property name= "hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.Country" ></mapping>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.CloudUser"></mapping>
</session-factory>
</hibernate-configuration>
This is HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory= buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static Session session=null;
private static SessionFactory buildSessionFactory(){
try{
Configuration configuration= new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry=new
StandardServiceRegistryBuilder().
applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory (serviceRegistry);
}
catch (Throwable ex){
System.err.println("Failed to cerate SessionFactory object"+ ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session openSession(){
return sessionFactory.openSession();
}
public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public static void close(){
sessionFactory.close();
}
}
The class Test.java:
package tn.ensi.cloudtrustproject.util;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Test {
static Session session= HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("from tn.ensi.cloudtrustproject.dao.entity.Country
").list();
}
}
The entity class:
package tn.ensi.cloudtrustproject.dao.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="country")
public class Country implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
#Column(name="countryid")
private Integer countryId ;
#Column(name="countrydes")
private String countryDes;
public Country(Integer countryId, String countryDes) {
super();
this.countryId = countryId;
this.countryDes = countryDes;
}
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Integer getCountryId() {
return countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
public String getCountryDes() {
return countryDes;
}
public void setCountryDes(String countryDes) {
this.countryDes = countryDes;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "Country [countryId=" + countryId + ", countryDes=" + countryDes
+ "]";
}
}
The project:
project
The table is created:
Table country
you have mentioned configuration file exists in config/hibernate.cfg.xml. Please check whether it is existing in same location.
I have a question about my hibernate mapping, I am creating a project with Spring and hibernate, I am facing a issue that I can solve it so far and I couldn't find someone able to help me so far, so I mapped the database and did everything as expected but I am receiving this message:
HHH000183: no persistent classes found for query class: FROM com.inbox.model.Estado
My hibernate.cfg.xml is like this
<?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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://inboxmysqldb.c4lcntgo83fr.us-west-2.rds.amazonaws.com</property>
<property name="hibernate.connection.username">inboxuser</property>
<property name="hibernate.connection.password">xxxxxx</property>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> -->
<property name="hibernate.show_sql">false</property>
<!-- <property name="hibernate.hbm2ddl.auto">true</property>-->
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Mapping files -->
<!-- <mapping class="com.inbox.model.Box"/> -->
<mapping class="com.inbox.model.Estado"/>
</session-factory>
</hibernate-configuration>
My class is mapped like this:
package com.inbox.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity(name="com.inbox.model.Estado")
#Table(name = "estado",
uniqueConstraints={#UniqueConstraint(columnNames={"id"})})
public class Estado implements IdentifierInterface, Serializable{
/**
*
*/
private static final long serialVersionUID = 3625863483844458267L;
#Id
#GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
#Column(name="id", nullable=false, unique=true, length=11)
private Integer id;
#Column(name="nome", length=20, nullable=true)
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() {
return getSessionFactory().openSession();
}
}
As requested follow the query
public T findById(int id) {
Session session = HibernateUtil.getSession();
session.beginTransaction();
try {
Query byIdQuery = session.createQuery("FROM " + entityClassName + " as c WHERE c.id = :id");
byIdQuery.setParameter("id", id);
return (T) byIdQuery.uniqueResult();
} catch (Exception e) {
throw new InboxException(e);
} finally {
session.close();
}
}
I ran out of ideas to try fix.
Thanks in advance
I am trying to learn hibernate and i'm having a problem with hibernate annotations, the thing is that hibernate doesn't seam to recognise my entity User
package com.mycompanyname.myapp;
import java.util.Date;
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="FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_ID")
private Long userId;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="BIRTH_DATE")
private Date birthDate;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name="CREATED_DATE")
private Date createdDate;
#Column(name="CREATED_BY")
private String createdBy;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
this is my main
package com.mycompanyname.myapp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import com.mycompanyname.myapp.User;
public class Application {
public static void main(String[] args) {
// A SessionFactory is set up once for an application!
SessionFactory sessionFactory =null;
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 );
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
//session.close();
}
}
this is my 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 name="HibernateUtil">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">database</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/financialanalysis</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<mapping class="com.mycompanyname.myapp.User"/>
</session-factory>
</hibernate-configuration>
this exception keeps popping out
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.mycompanyname.myapp.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
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:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.mycompanyname.myapp.Application.main(Application.java:32)
so what am i doing wrong ?
I think there is an issue with the way you configure SessionFactory. I created a sample application based on the source code you have provided. I suspect there is something wrong with this line.
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
So I would take a different approach to configure session factory like this.
SessionFactory sessionFactory =null;
try {
Configuration configuration = new Configuration();
configuration.configure();
final ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(registry);
}
catch (Exception e) {
e.printStackTrace();
sessionFactory.close();
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
session.close();
Looking at the source code configuration.configure() method also finds the default hibernate.cfg.xml file on the classpath as new StandardServiceRegistryBuilder().configure() does. With these configurations in place now you should be able to persist/load/update entities without any issue.
I tested this configuration with a quick and dirty sample application using Hibernate 4.0.
Just use this to build a session factory
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
It works for Hibernate 4 and Hibernate 5. This code has a deprecation in Hibernate 4, but this deprecation is removed in Hibernate 5.
configure your User class like-
Configuration cfg=new Configuration();
cfg.addAnnotatedClass(com.mycompanyname.myapp.User.class);
cfg.configure();
hope it help.
I am new to Java Hibernate. I setup a dynamic web project in eclipse and trying to insert a row in mysql db. I am getting the following error when I run my code on server.
java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ClassLoaderDelegate
org.hibernate.boot.internal.MetadataBuilderImpl.(MetadataBuilderImpl.java:127)
org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:655)
My hibernate.cfg.xml
<session-factory>
<!-- Database connection settings -->
<property name='connection.driver_class'>com.mysql.jdbc.Driver</property>
<property name='connection.url'>jdbc:mysql://localhost:3306/bornscientific</property>
<property name='connection.username'>root</property>
<property name='connection.password'></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>
<!-- Echo all executed SQL to stdout -->
<property name='show_sql'>true</property>
<!-- Mapping files -->
<mapping class="com.bornscientific.persistence.beans.Tags"/>
</session-factory>
My entity class
package com.bornscientific.persistence.beans;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "TAGS")
public class Tags implements Serializable
{
private Long id;
private String name;
public Tags()
{
}
#Id
#SequenceGenerator(name="seq1",sequenceName="HIB_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq1")
#Column(name = "TAG_ID", unique = true, nullable = false)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#Column(name = "NAME", unique = true, length = 100, nullable = false)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
And my main method is
public static void test() throws Exception
{
try
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.getTransaction();
tx.begin();
Tags tags = new Tags();
tags.setName("TAG_1");
session.save(tags);
tx.commit();
System.out.println("Saved successfully...");
}
catch(Exception e)
{
//System.out.println(e)
e.printStackTrace();
}
}
HibernateUtil.java
package com.bornscientific.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw ex;
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
And this is the library referenced.
Please help me fix this issue. I have searched through google and could not find a solution.