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
Related
I'm really new to hibernate and try to understand how it works. But know I faced with the problem.
First of all, I have such mapping:
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Author() {
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
But then, when I tried to save this entitye with session.save(), hibernate showed me error like
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "author" violates not-null constraint
Failing row contains (null, hello!).
So I decided to notice, why hibernate doesn't increment the id automaticy and recognized that POSTGRESQL doesn't suppert annotation GenerationType.IDENTITY. So I changet it to the GenerationType.SEQUENCE. The error was gone, but entity wasn't saved.
So here's 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/hibernate?useSSL=false
&serverTimezone=UTC</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="connection.username">postgres</property>
<property name="connection.password">4122</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="hibernate.entity.Author"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Here's HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.build();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
return sessionFactoryBuilder.build();
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
And here's the Main.java, where I call the hibernate functions:
public class Main {
public static void main(String[] args) {
try(Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
Author author = new Author();
author.setName("hello!");
session.save(author);
tx.commit();
System.out.println(session.get(Author.class, 1L));
}
}
}
After program execution it prints me null and there is no entity in database:
If you know, what can be the problem, please tell me. I'd really apreciate it!
I think the reason is setter for id missing:
public long setId(long id) {
this.id = id;
}
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'm trying to create a small project with hibernate, but i got that error "Type is not mapped [select o from Type o]", I added mapping in hibernate.cfg.xml but still error.
Type.java:
package com.formation.gestionprojet.doa.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Type")
public class Type implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String name;
private String description;
private String active;
public Type() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
}
hibernate.org.xml:
<?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 setting -->
<property name ="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/gestion_projet?createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name= "connection.password">root</property>
<!-- 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>
<!-- Drope and re-create the database -->
<property name="hbm2ddl.auto">update</property>
<!-- mapping -->
<mapping class= "com.formation.gestionprojet.doa.entity.Type"/>
</session-factory>
</hibernate-configuration>
hibernateUtil.java:
package com.formation.gestionprojet.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#SuppressWarnings("deprecation")
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
Configuration configuration = new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException ex)
{
System.err.println("Error creating Session: " + 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(){
if(sessionFactory!=null){
sessionFactory.close();
}
}
}
Test.Java
package com.formation.gestionprojet.utils;
import org.hibernate.Session;
public class Test {
static Session session = HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("select o from Type o").list();
}
}
solved ! the problem was the version of hibernate that I used so I change it, a change in HibernateUtil.
This question is different from the other questions on the same topic of MappingException: Unknown entity because I have this line in my hibernate config:
<mapping class="bbb.Students" />
My entity class is as follows:
package bbb;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Students")
public class Students implements java.io.Serializable {
private String id;
private String name;
private String number;
#Id
#Column(name = "ID", unique = true, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "NUMBER", nullable = false)
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
I have the database test and the table Students manually created.
The error is:
org.hibernate.MappingException: Unknown entity: bbb.Students
Exception in thread "main" org.hibernate.MappingException: Unknown entity: bbb.Students
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
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:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at bbb.App.main(App.java:39)
The Main class is as follows:
package bbb;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class App
{
public static void main( String[] args )
{
System.out.println("Hibernate one to one (Annotation)");
Configuration conf = new Configuration();
SessionFactory sf = conf.configure()
.buildSessionFactory(
new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties())
.build());
Session session = sf.openSession();
session.beginTransaction();
Students s = new Students();
s.setId("1");
s.setName("Joe");
s.setNumber("12345");
session.save(s);
session.getTransaction().commit();
System.out.println("Done");
}
}
The full hibernate.config is as follows:
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<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>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="bbb.Students" />
</session-factory>
</hibernate-configuration>
Just imported your Students class in a Hibernate based project. Everything work fine. Before running the application, I created schema "test" manually. Post a class with the main method. Probably something is wrong in it.
Update:
Imported your's main method. The application still works. Can't reproduce an issue.
import bbb.Students;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
ourSessionFactory = new Configuration().
configure("hibernate.cfg.xml").
buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
Transaction transaction= session.beginTransaction();
Students student = new Students();
student.setName("Vasua");
student.setNumber("13");
student.setId("1");
session.save(student);
transaction.commit();
} finally {
session.close();
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernte Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:mysql://localhost/stack
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
root
</property>
<!-- DB schema will be updated if needed -->
<property name="hbm2ddl.auto">update</property>
<mapping class="bbb.Students"/>
</session-factory>
</hibernate-configuration>
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.