How to Resolve "org.hibernate.MappingException: Unknown entity" Error? [duplicate] - java

This question already has answers here:
Hibernate unknown entity (not missing #Entity or import javax.persistence.Entity )
(7 answers)
Closed 7 years ago.
I am getting this below Exception.am using Struts2 and Hibernate for developing web application.can any one help me to resolve this Issue ?
org.hibernate.MappingException: Unknown entity: Pojo.USER [Packagename.entityClassname]
Hibernate.cfg.xml file Content :-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/databasename
</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="cache.provider_class">
org.hibernate.cache.HashtableCacheProvider</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
</session-factory>
</hibernate-configuration>
USER's Entity Class content :-
package Pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="user")
public class USER {
#Id
#GeneratedValue
#Column(name="USER_ID")
private int id;
#Column(name="USER_NAME")
private String name;
#Column(name="USER_PASSWORD")
private String password;
#Column(name="USER_GENDER")
private String gender;
#Column(name="USER_COUNTRY")
private String country;
#Column(name="USER_ABOUT_YOU")
private String aboutyou;
#Column(name="USER_MAILING_LIST")
private boolean mailinglist;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutyou() {
return aboutyou;
}
public void setAboutyou(String aboutyou) {
this.aboutyou = aboutyou;
}
public boolean isMailinglist() {
return mailinglist;
}
public void setMailinglist(boolean mailinglist) {
this.mailinglist = mailinglist;
}
}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/databasename
</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="cache.provider_class">
org.hibernate.cache.HashtableCacheProvider</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<mapping class="Pojo.User">
</session-factory>
</hibernate-configuration>
Use mapping class,so that hibernate will come to know your entity class--> <mapping class="Pojo.User">

USER entity is unknown to your Hibernate session. Add <mapping class="Pojo.USER"/> in session-factory configuration.
...
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<mapping class="Pojo.USER"/>
</session-factory>
</hibernate-configuration>

Related

Hibernate says database.table doesn't exist

The Situation
Ok, so I am learning Hibernate(from 2 days so pardon any blunder), I am using mysql database and just trying tocreate a table Employee and make an entry in database(A demonstration).
Here are the codes
POJO:
package com.sopra.pojo;
import javax.persistence.*;
#Entity
#Table(name = "EMPLOYEE")
public class Employee {
#Id
private int Id;
private String firstName;
private String lastName;
private int salary;
public int getId() {
return Id;
}
public void setId(int id) {
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
hibernate.cfg.xml which is in src
<?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.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name = "hibernate.hbm2ddl.auto">create</property>
<mapping class="com.sopra.pojo.Employee" />
</session-factory>
</hibernate-configuration>
EmployeeDBManager.java
package com.sopra.pojo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmployeeDBManager {
public static void main(String[] args) {
Employee e = new Employee();
e.setFirstName("Salim");
e.setId(672);
e.setLastName("Shamim");
e.setSalary(266);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(e);
tx.commit();
session.close();
}
}
The Error
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.employee' doesn't exist
I've tried
use this in cfg file : <property name="hibernate.hbm2ddl.auto">update</property>
What is interesting is when I manually create the table in mysql using workbench, hibernate does drops it as when i use drop command it says the table doesn't exists.
I can't figure out where the glitch might be(newbie and internet didn't helped).
Please mention any additional details required in comments.
Please help!
Thanks.
I made it worked, I am not sure if it's a proper answer but since it got it working I am posting it as an answer.
I made two changes
I was using hibernate version 5.2.12 so I changed it to 4.2.0 and added jars from two more folders which earlier I hadn't (In summary I have now imported Jars from :optional, provided & required folder in hibernate user library)
I overlooked a url mistake which was
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
In the dtd url I have not added www. It should have been
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">`
So, my mistake.
Anyway, comments regarding improving this answer and why it made it work are deeply appreciated.
add different auto option of hibernate,
Use instead of create , update or create-drop
<property name="hibernate.hbm2ddl.auto">update</property>
or
<property name="hibernate.hbm2ddl.auto">create-drop</property>
You can read more about it here

org.hibernate.exception.JDBCConnectionException: Cannot open connection

for testing purpose i wrote very small code,which repeatedly throws exception related to jdbc driver.
package sally;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class MainClass {
public static void main(String args[]){
try{
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Employee ee=new Employee("abx","asd",2000);
session.save(ee);
tx.commit();
}catch(Exception e){
e.printStackTrace();
}
}
}
This is my ben/pojo class for mapping
package sally;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="sally.Employee" table="EMPLOYEE">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
and this is cfg file for pojo class:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="sally.Employee"></mapping>
</session-factory>
but every time i am running the code it throws exxception :
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
org.hibernate.exception.JDBCConnectionException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at sally.MainClass.main(MainClass.java:12)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
can any body tell whats wrong here???
this is db column list : first_name last_name salary.
You need to put the mysql JDBC driver JAR on your classpath
name for the driver class must be updated as well as server time zone (for me this is insane but it has to be done
<?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.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hibernate?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
</session-factory>
</hibernate-configuration>
org.hibernate.exception.JDBCConnectionException: Cannot open connection It occurs when you have not started the xampp and MySql.

Fetch results from session.load using Hibernate

I'm trying to fetch resultset by making the query in Hibernate like
String id = "10";
Person per = session.load(Person .class, id); // This is wrong, because it accepts only an integer, not a string.
But, I require to fetch results using session.load by passing a string, because second level cache is not triggering when I try to fetch as
Criteria cr = session.createCriteria(Person.class);
cr.add(Restrictions.like("userId", id));
List<?> results = cr.list();
Person class
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
#Entity
#Table(name = "person")
public class Person {
#Override
public String toString() {
return "Personalisation [id=" + id + ", userId=" + userId
+ ", courseId=" + courseId + ", courseValue=" + courseValue
+ "]";
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String userId;
private String courseId;
private String courseValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getCourseValue() {
return courseValue;
}
public void setCourseValue(String courseValue) {
this.courseValue = courseValue;
}
}
<?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/intu</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Ehcache config -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/ehcache.xml</property>
<!-- c3p0 Connection pool config -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="hibernate.c3p0.privilegeSpawnedThreads">true</property>
<property name="hibernate.c3p0.contextClassLoaderSource">library</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.intu.Dashboard" />
<mapping class="com.intu.Employee"/>
<mapping class="com.intu.Person"/>
The above code is working, but not by second level cache, each time its hitting DB.
What steps do I need to do to get it done? Is there any other way
Please call cr.setCacheable(true) after cr.add(Restrictions.like("userId", id)).

Exception in thread "main" org.hibernate.MappingException: invalid configuration

Hi Iam trying to run my hiberanate application i am getting the Hibernate Exception.
my hibernate.cfg.xml file is
<?xml version='1.0' encoding='UTF-8'?>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- <mapping resource="config\\hibernate.hbm.xml"/ -->
<mapping resource="config\\employee.hbm.xml"/>>
</session-factory>
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-mapping>
<class name = "com.javatpoint.mypackage.Employee" table = "emp_TPCH" discriminator-value="emp">
<id name = "id">
<generator class = "increment">
</generator>
</id>
<discriminator column="type" type= "string"></discriminator>
<property name ="Name"></property>
<subclass name = "com.javatpoint.mypackage.Regular_Employee" discriminator-value="reg_emp">
<property name = "salary"></property>
<property name = "bonus"></property>
</subclass>
<subclass name = "com.javatpoint.mypackage.Contract_Employee" discriminator-value = "con_emp">
<property name = "pay_Per_Hour"></property>
<property name = "contact_Duration"></property>
</subclass>
</class>
</hibernate-mapping>
Employee.java is
package com.javatpoint.mpackage;
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
}
Contract_Employee.java
package com.javatpoint.mpackage;
public class Contract_Employee extends Employee {
private float pay_Per_Hour;
private String contact_Duration;
public float getPay_Per_Hour() {
return pay_Per_Hour;
}
public void setPay_Per_Hour(float pay_Per_Hour) {
this.pay_Per_Hour = pay_Per_Hour;
}
public String getContact_Duration() {
return contact_Duration;
}
public void setContact_Duration(String contact_Duration) {
this.contact_Duration = contact_Duration;
}
}
Regular Employee.js is
package com.javatpoint.mpackage;
public class Regular_Employee extends Employee {
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
}
Guys please help me to come out of this Exception.
Include this as the second line in your file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
There are maybe other errors, but this line is invalid:
<mapping resource="config\\employee.hbm.xml"/>>
^-- two brackets here
Also, the resource should be config/employee.hbm.xml. The resource is a classpath resource, using forward slashes as path separator.

org.hibernate.InvalidMappingException: Could not parse mapping document from resource

I switched the mapping in my code from xml resource to annotations and got that exception. I don't see the error. I think you can figure it out from my code:
hibernate.cfg.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>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">####</property>
<property name="hibernate.connection.username">##</property>
<property name="hibernate.connection.password">###</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.show_sql">true</property>
<mapping class="max.Trade" file="" jar="" package="max" resource=""/>
</session-factory>
</hibernate-configuration>
Trade.java
#Entity
#Table(name="TRADES", schema="PGT")
public class Trade implements java.io.Serializable
{
private long murexId;
private String type;
private String portfolio;
public Trade() {
}
public Trade(long murexId) {
this.murexId = murexId;
}
public Trade(long murexId, String type, String portfolio) {
this.murexId = murexId;
this.type = type;
this.portfolio = portfolio; }
#Id
#Column(name="MUREX_ID", unique=true, nullable=false, precision=10, scale=0)
public long getMurexId() {
return this.murexId;
}
public void setMurexId(long murexId) {
this.murexId = murexId;
}
#Column(name="TYPE", length=32)
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
#Column(name="PORTFOLIO", length=32)
public String getPortfolio() {
return this.portfolio;
}
public void setPortfolio(String portfolio) {
this.portfolio = portfolio;
}
}
I will really appreciate any help.
Thanks!
replace mapping definition(tag) as
<mapping class="max.Trade"/>

Categories