Maybe it is common question with clear answers on stackoverflow. But after 2 hours searching I could not find the answer.
I am new in hibernate and using maven. I am using this tutorial that is annotation base, with some changes. However, it is not working. I used some xml mapping file.
I even add Employee.hbm.xml that is for hibernate xml-base.
At this line >> session.persist(e1); it throw exception
Employee.java
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
#Table(name = "employee")
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
#DiscriminatorValue(value="employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "name")
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;
}
}
Main.java
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Main {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setName("sonoo");
Regular_Employee e2 = new Regular_Employee();
e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Contract_Employee e3 = new Contract_Employee();
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="employee" discriminator-value="employee">
<id name="id">
<generator class="increment"></generator>
</id>
<discriminator column="type" type="string"></discriminator>
<property name="name"></property>
<subclass name="Regular_Employee" discriminator-value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
<subclass name="Contract_Employee" discriminator-value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>
</class>
</hibernate-mapping>
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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="Employee.hbm.xml"/>
<mapping class="Employee"/>
<mapping class="Contract_Employee"/>
<mapping class="Regular_Employee"/>
</session-factory>
</hibernate-configuration>
Exception text
Exception in thread "main" org.hibernate.MappingException: Unknown entity: Employee
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1529)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:225)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:510)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:99)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753)
at Main.main(Main.java:36)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
The problem with this
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory(serviceRegistry);
You try to do the configuration twice. This is not neccessary
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
You can't use this way to configure Hibernate 5. Just do this for the configuration
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
How to configure Hibernate 5
Just put configuration.addResource("Employee.hbm.xml") after configuration.configure("hibernate.cfg.xml")
Related
I am using Hibernate and PostgresSQL and am trying to create a table by .xml with no success.
I don't see an error when I start Main.class. Maybe I should use another version of Hibernate?
I'm using Gradle and added in dependencies for the latest versions of hibernate-core, hibernate-entitymanager, and hibernate-validator.
I have been watching video published in 2016: maybe there's a problem in it.
Hibernate cfg:
<?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.PostgreSQL9Dialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.username">pavel</property>
<property name="connection.password">31228900</property>
<property name="connection.pool_size">10</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="planetofUsers.cfg.xml"/>
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateLesson.Planet" table="planet">
<id name="id" >
<generator class="native" />
</id>
<property name="age" column="age" type="int" />
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="last_name" type="string" />
</class>
</hibernate-mapping>
Java classes:
import lombok.Data;
import lombok.experimental.FieldDefaults;
import static lombok.AccessLevel.PRIVATE;
#Data
#FieldDefaults(level = PRIVATE)
public class Planet {
long id;
int age;
String firstName;
String
import lombok.experimental.FieldDefaults;
import org.hibernate.SessionFactory;
import static lombok.AccessLevel.PRIVATE;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
}
}
package hibernateLesson;
import lombok.experimental.FieldDefaults;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import static lombok.AccessLevel.PRIVATE;
#FieldDefaults(level = PRIVATE)
public class HibernateUtil {
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;
}
}
Use below setting :
hibernate.hbm2ddl.auto = create
I am working with hibernate. I create a table called UserDetails (POJO class) with id and name. I am however finding it difficult to execute the program because it is giving me this error -
Exception in thread "main" org.hibernate.MappingNotFoundException: resource:
hibernate_hbm.xml.UserDetails.hbm.xml not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:740)
at
org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2197)
at
org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2169)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2149)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2102)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2017)
at hibernate_hbm.xml.A.main(A.java:19)
All the files are in - hibernate_hbm.xml package -my files are :
[1] UserDetails-
package hibernate_hbm.xml;
public class UserDetails {
private int id;
private String name;
//setter & getters
}
[2]A.java file that contains the UserDetails Objects and SessionFactory -
package hibernate_hbm.xml;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class A {
public static void main(String[] args) {
UserDetails user1 = new UserDetails();
user1.setId(101);
user1.setName("Mark");
UserDetails user2 = new UserDetails();
user2.setId(102);
user2.setName("Cynthiya");
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user1);
session.save(user2);
session.getTransaction().commit();
session.close();
}
}
[3]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.connection.url">jdbc:mysql:
//localhost:3306/testingcampus</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property
name="hibernate.current_session_context_class">thread</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="hibernate_hbm.xml.UserDetails.hbm.xml" />
</session-factory>
</hibernate-configuration>
[4] UserDetails.hbm.xml file -
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_hbm.xml.UserDetails" table="UserInfo">
<id name="id"></id>
<property name="name"></property>
</class>
</hibernate-mapping>
As that file is on class path try the mapping resource value in hibernate.cfg.xml as below :
"classpath:UserDetails.hbm.xml"
<mapping resource="classpath:UserDetails.hbm.xml" />
Do share the folder structure that you followed as that'll help with the exact path to be used
i have a problem and i need your help.i use eclipse 4.5.1. hibernate5.1
and here is the code
Exception in thread "main" org.hibernate.MappingException: Unknown entity: net.runze.hb1.entity.News
public class NewsManager {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
Session sess = sf.openSession();
Transaction ta = sess.beginTransaction();
News n = new News();
n.setTitle("Aliens");
n.setContent("hahahaha!");
sess.save(n); // here is where it threw exception
ta.commit();
sess.close();
sf.close();
}
}
and i use annotation to the entity class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="news_inf")
public class News {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String title;
private String content;
// getters and setters...
}
here 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>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.c3p0.aquire_increment">2</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<mapping class="net.runze.hb1.entity.News" />
</session-factory>
</hibernate-configuration>
they says this problem will happen when my #Entity import the wrong package,or the hibernate.cfg.xml forgot the "mapping". both them i made it right but it still don't work.
It is simply :)
Configuration conf = new Configuration()
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
Change to
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
you have to specify where your configuration file is:
onfiguration conf = new Configuration().configure("[your package]/hibernate.cfg.xml");
When I tried my first hibernate program and I got this error.
My program simply insert empID,first_name,second_name(table names) and using MySQL database.
Tried lot of solutions sill getting this error.
mapping 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>
<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">anandhu</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="emp">
<id name="empID" column="empID" type="int">
<generator class="assigned"></generator>
</id>
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
</class>
</hibernate-mapping>
This is my persistence class
public class Employee {
private int empID;
private String firstName;
private String lastName;
public int getID(){
return empID;
}
public void setID(int empID){
this.empID = empID;
}
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;
}
}
This is my test class
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class EmployeeTest {
public static void main(String[] args) {
Configuration cf = new Configuration();
cf.configure("employee.cfg.xml");
SessionFactory factory = cf.buildSessionFactory();
Session session = factory.openSession();
Employee employee = new Employee();
employee.setID(30);
employee.setFirstName("raju");
employee.setLastName("ryan");
Transaction transaction = session.beginTransaction();
session.save(employee);
System.out.println("updated");
transaction.commit();
session.close();
factory.close();
}
}
stack trace
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: employee.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.anandhu.hibernateproject.EmployeeTest.main(EmployeeTest.java:16)
Caused by: org.dom4j.DocumentException: Error on line 3 of document :
The processing instruction target matching "[xX][mM][lL]" is not allowed.
Nested exception:
The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
The problem with this lines
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
Should be
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="second_name" type="string" />
It would be more simply to find a solution if you show all stacktrace.
You can find examples of working with a configuration and a session here.
Upated
I check this mapping and it works fine. Looks like you have incorrect symbols (may be spaces) in the xml header. May be this will be helpfull Error: The processing instruction target matching “[xX][mM][lL]” is not allowed.
Trying to learn Hibernate, i am trying to learn how to execute NamedQuries but evertime i am getting Exception in thread "main" org.hibernate.MappingException: Named query not known.Please help me out here
Error (only the message, not showing complete stack)
Exception in thread "main" org.hibernate.MappingException: Named query not known: hibernate_tut_emp.Employee.FindCountOfNames
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
at hibernate_tut_emp.MyOps.main(MyOps.java:20)
Employee.java
package hibernate_tut_emp;
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.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#Table(name="Hib1")
#NamedQueries({
#NamedQuery(name="GetDetailsByName" , query="select * from hib1 h where h.name=:name"),
#NamedQuery(name="FindCountOfNames", query="select count(1) as cnt from hib1 h where h.name=:name")
})
public class Employee {
private int id;
private String name;
#Id
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String empName) {
this.name = empName;
}
}
MyOps.java
package hibernate_tut_emp;
import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class MyOps {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a name : ");
String name = scnr.next();
SessionFactory ses = HibernateUtil.getSessionFactory();
Session session = ses.openSession();
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
query.setString("name", name);
int count = ((Integer)query.iterate().next()).intValue();
System.out.println("count : "+count);
}
}
employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_tut_emp.Employee" table="hib1">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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">mayank</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>
<!-- 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>
<!-- 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>
<mapping class="hibernate_tut_emp.Employee" />
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I googled out everything possible but i think i am overlooking some basic stuff.Any indication in right direction is appreciated! :)
One thing i considered is that if i have defined in class file NamedQueries, i do not need to mention it in xml file.Please correct me if i am wrong!
There are several issues here:
Your named queries should use entities not tables. If you want native queries you should use NamedNativeQuery instead.
You don't need to supply the entity name when fetching the query.
Change this:
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
to:
Query query = session.getNamedQuery("FindCountOfNames");