I am creating a simple Laptop-info form using JSF and Hibernate in IntelliJ IDEA. When I execute my project then I face this error:
javax.servlet.ServletException: java.lang.ExceptionInInitializerError
javax.faces.webapp.FacesServlet.service(FacesServlet.java:667)
Here I list the required files and directory structure.
LaptopDAO.java
package Dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import pojo.Laptop;
import util.HibernateUtil;
public class LaptopDAO {
public void SaveLaptop(Laptop laptop)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.save(laptop);
t.commit();
session.close();
}
}
Laptop.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="pojo.Laptop" table="laptopdb">
<id name="id"><generator class="increment"></generator></id>
<property name="company">
<column name="laptopcompany"></column>
</property>
<property name="model">
<column name="laptopmodel"></column>
</property>
<property name="ram">
<column name="laptopram"></column>
</property>
<property name="hd">
<column name="laptophd"></column>
</property>
</class>
</hibernate-mapping>
Class LaptopBean
package LaptopMBean;
import Dao.LaptopDAO;
import pojo.Laptop;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "laptopBean")
public class LaptopBean {
Laptop l;
public LaptopBean()
{
l = new Laptop();
}
public Laptop getL()
{
return l;
}
public void setL(Laptop l)
{
this.l = l;
}
public void savetoDB()
{
LaptopDAO ld = new LaptopDAO();
ld.SaveLaptop(l);
System.out.print("Success");
}
}
Class Laptop
package pojo;
public class Laptop {
int id;
String company;
String model;
String ram;
String hd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getHd() {
return hd;
}
public void setHd(String hd) {
this.hd = hd;
}
}
Class HibernateUtil
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory buildSessionFactory()
{
try
{
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed. " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
File 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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/laptop</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="connection.pool_size">1</property>
<mapping resource="hbm/laptop.hbm.xml"/>
</session-factory>
</hibernate-configuration>
StackTrace
23:44:51,700 INFO [org.hibernate.validator.internal.util.Version] (default
task-4) HV000001: Hibernate Validator 5.1.3.Final
23:44:52,080 INFO [org.hibernate.Version] (default task-4) HHH000412:
Hibernate Core {5.4.0.Final}
23:44:52,084 INFO [org.hibernate.cfg.Environment] (default task-4)
HHH000206: hibernate.properties not found
23:44:52,091 ERROR [stderr] (default task-4) Initial SessionFactory creation
failed.java.lang.NoClassDefFoundError:
net/bytebuddy/NamingStrategy$SuffixingRandom$BaseNameResolver
23:44:52,092 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle]
(default task-4) #{laptopBean.savetoDB()}:
java.lang.ExceptionInInitializerError: javax.faces.FacesException: #
{laptopBean.savetoDB()}:
I have added all libraries. How can I find out what the problem is?
Related
Not sure what is wrong. I am getting the exception given:
org.hibernate.MappingException: Unknown entity: org.hibernate.employee
How to fix it? I created client.java. I created the table that mapped that matched the client. I have created the mapping and added the mapping
hibernateutil.java coding
package org.hibernate.test.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class hibernateutil {
private static SessionFactory sessionfactory;
public static SessionFactory getSessionFactory(){
if(sessionfactory == null){
synchronized(hibernateutil.class){
if(sessionfactory == null){
try {
Configuration conf=new Configuration().configure();
StandardServiceRegistryBuilder builder= new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties());
sessionfactory = conf.buildSessionFactory(builder.build());
}catch (Throwable th){
th.printStackTrace();
throw new ExceptionInInitializerError();
}
}
return sessionfactory;
}
}
else{
return sessionfactory;
}
}
}
employee.java
package org.hibernate;
public class employee {
private int id;
private String firstname;
private String lastname;
private int salary;
public employee(){}
public employee(int id,String firstname,String lastname,int salary)
{
this.id=id;
this.firstname=firstname;
this.lastname=lastname;
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 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
<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">javaguy</property>
<property name="connection.password"></property>
<property name="hibernate.jdbc.batch_size">100</property>
<property name="connection.pool_size">1</property>
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 20, 2016 7:56:20 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="employee" table="EMPLOYEE">
<id name="id" type="int">
<column name="EMP_ID" />
<generator class="assigned" />
</id>
<property name="firstname" type="java.lang.String">
<column name="FIRST_NAME" />
</property>
<property name="lastname" type="java.lang.String">
<column name="LAST_NAME" />
</property>
<property name="salary" type="int">
<column name="SALARY" />
</property>
</class>
</hibernate-mapping>
client.java
package learn;
import org.hibernate.Session;
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.test.util.hibernateutil;
import org.hibernate.*;
public class client {
private static SessionFactory factory;
public static void main(String[] args) {
factory = hibernateutil.getSessionFactory();
client a = new client();
// Add few employee records in data base
a.addemployee(1,"Sai","Nathan",5000);
a.addemployee(2,"Sai","kumar",6000);
a.addemployee(3,"Santhosh","Kumar",9000);
// List down all employees
/*a.listemployee();
// update employee's record
a.updateemployee(1,20000);
// Delete an employee
a.deleteemployee(3);
// List down all employees
a.listemployee();*/
System.out.println("Finished");
}
/* Method to CREATE an employee in the database */
public Integer addemployee(int id, String fname,String lname,int salary)
{
Session session= factory.openSession();
Transaction tx=session.beginTransaction();
employee e1= new employee(id,fname,lname,salary);
Integer empid=(Integer)session.save(e1);
tx.commit();
session.close();
return empid;
}
/* Method to READ all the employees */
public void listemployee(){
Session session = factory.openSession();
List<employee> emplist = session.createQuery("FROM Employee").list();
for(employee emp:emplist){
System.out.print("First name" +emp.getFirstname());
System.out.print("Last name" +emp.getLastname());
System.out.println("Salary" +emp.getSalary());
}
session.close();
}
/* Method to UPDATE salary for an employee */
public void updateemployee(Integer id,Integer salary)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
employee emp = (employee)session.get(employee.class, id);
emp.setSalary(salary);
session.update(emp);
tx.commit();
session.close();
}
public void deleteemployee(Integer id)
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
employee emp = (employee)session.get(employee.class, id);
session.delete(emp);
tx.commit();
}
}
error:
project path:
<class name="employee">
should have full package name (path) and all classes should starts with a capital letter.
So it should be like:
package mypackage;
public class Employee
{
...
}
<class name="mypackage.Employee" ...>
Test:
import java.util.GregorianCalendar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import it.s.monitoringDoor.model.Door_Open;
import it.s.monitoringDoor.model.HibernateUtilities;
public class TestHibernate {
public static void main(String[] args){
SessionFactory factory = HibernateUtilities.getSessionFactory();
Door_Open d = new Door_Open();
d.setId(1);
d.setId_door(1);;
d.setTimestamp(getTime());
Session s = factory.openSession();
Transaction t = s.getTransaction();
t.begin();
s.save(d);
t.commit();
}
private static Date getTime(){
GregorianCalendar gc = new GregorianCalendar();
return gc.getTime();
}
}
HibernateUtilities:
package it.s.monitoringDoor.model;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtilities {
//XML based configuration
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory;
}
}
The Pojo class Door_Open.java
package it.selco.monitoringDoor.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "door_open")
public class Door_Open {
//---------------- Instance variables ----------------
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "id_door", nullable = false)
private int id_door;
#Column(name = "id_door", nullable = false)
private Date timestamp;
//-------------------- Constructor --------------------
public Door_Open (){
;
}
public Door_Open(int id_door, Date timestamp) {
setId_door(id_door);
setTimestamp(timestamp);
}
//--------------------- Get & Set ---------------------
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#SuppressWarnings("unused")
private int getId_door() {
return id_door;
}
public void setId_door(int id_door) {
this.id_door = id_door;
}
#SuppressWarnings("unused")
private Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
//--------------------- Methods ----------------------
//TODO Auto-generated methods variables block
}
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="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/monitor_door</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- ############################################
# mapping files with external dependencies #
############################################ -->
<mapping resource="it/s/monitoringDoor/model/Door_Open.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Door_Open.hbm.xml
<?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="Door_Open" table="door_open" schema="monitor_door">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="id_door" column="id_door" type="int" not-null="true"/>
<property name="timestamp" column="timestamp" type="timestamp" not-null="true"/>
</class>
</hibernate-mapping>
When I run the test is returned me the following error.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: it.s.monitoringDoor.model.Door_Open
[...]
some advice?
Look at the package of your Door_Open class, it is: it.selco.monitoringDoor.model while in hibernate.cfg.xml the Door_Open.hbm.xml file is at: <mapping resource="it/s/monitoringDoor/model/Door_Open.hbm.xml"/>. The package and the mapping resource path do not match, they should be the same e.g. it/selco/monitoringDoor/model/Door_Open.hbm.xml
and of course move the Door_Open.hbm.xml to be in the same path as its class.
Hope this helps.
PS, why are you using both annotations (e.g. #Entity) and hbm mapping for your class? I think you should choose one not both.
This is my first time trying out Hibernate with Eclipse and the following are the things I did:
Created a Java Bean called Student.java which is as follows:
package com.jwt.hibernate;
public class Student {
private long id;
private String name;
private String degree;
private String roll;
private String phone;
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 getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Created a mapping file, Student.hbm.xml as follows:
<hibernate-mapping>
<class name="com.jwt.hibernate.Student" table="student">
<id column="ID" name="id" type="long" />
<property column="name" name="name" type="string" />
<property column="degree" name="degree" type="string" />
<property column="roll" name="roll" type="string" />
<property column="phone" name="phone" type="string" />
</class>
</hibernate-mapping>
3. Created the hibernate configuration file, hibernate.cfg.xml 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/hibernatetutorial</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>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create </property>
<mapping resource="com/jwt/hibernate/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Created the class SimpleTest.java which is as follows:
package com.jwt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class SimpleTest {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setName("Mukesh");
student.setRoll("101");
student.setPhone("8888");
student.setDegree("B.E");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
Now, when I try to run SimpleTest, I get the following error:
**INFO: HHH000412: Hibernate Core {4.3.7.Final}
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.cfg.Configuration.reset(Configuration.java:326)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:291)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:295)
at com.jwt.hibernate.SimpleTest.main(SimpleTest.java:11)
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Environment.<clinit>(Environment.java:221)
... 4 more**
I double checked and made sure that all the configuration and jar files were added to the classpath. So that is not the problem. I would really appreciate some insights as to what may have caused this problem and inturn, how to solve it.
Thanks in advance!
I would recommend updating to later version of SLF4J.
Or
Your Hibernate.cfg.xml is not on classpath. What folder is it in?
Edit :
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
This is actual exception in your code, If your Hibernate.cfg.xml is loaded then check for SELF4J version, Don't use user library to take your jar files, put all libraries in your lib folder and then configure those in class path.
You may find a Java Configuration of Hibernate to be more friendly. Here is an example of one that I did (Note: there are Spring annotations like #Autowired and #PostConstruct in this class so don't get confused):
public class HibernateConfigBean {
private static final Logger logger = Logger.getLogger(HibernateConfigBean.class);
#Autowired private Environment environment;
private SessionFactory sessionFactory;
private Configuration configuration;
#PostConstruct
private void init(){
configuration = new Configuration();
configuration.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
configuration.setProperty("hibernate.connection.driver_class", environment.getProperty("hibernate.connection.driver_class"));
configuration.setProperty("hibernate.connection.url", environment.getProperty("hibernate.connection.url"));
configuration.setProperty("hibernate.connection.username", environment.getProperty("db_username"));
configuration.setProperty("hibernate.connection.password", environment.getProperty("db_password"));
//Add additional Annotated Classes here
configuration.addAnnotatedClass(UserEntity.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}
//This should be visible outside of the package as it's only used by the GenerateDbSchema class
void generateSchema() throws Exception {
try{
new SchemaExport(configuration).create(false, true);
} catch (RuntimeException re){
throw new Exception(re);
}
}
}
Then I just put my values into a properties file :-)
I'm using myeclipse IDE
After executing my code i'm getting the below Exception
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.MappingException: Unknown entity:info.inetsolv.Emp
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister
(SessionFactoryImpl.java:628)
at org.hibernate.impl.SessionImpl.getEntityPersister
(SessionImpl.java:1366)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState
(AbstractSaveEventListener.java:535)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:93)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at info.inetsolv.InsertEmprecord.main(InsertEmprecord.java:22)
POJO CLASS
package info.inetsolv;
#SuppressWarnings("serial")
public class Emp implements java.io.Serializable {
// Fields
private Integer eno;
private String name;
private Double salary;
// Constructors
/** default constructor */
public Emp() {
}
/** minimal constructor */
public Emp(Integer eno) {
this.eno = eno;
}
/** full constructor */
public Emp(Integer eno, String name, Double salary) {
this.eno = eno;
this.name = name;
this.salary = salary;
}
// Property accessors
public Integer getEno() {
return this.eno;
}
public void setEno(Integer eno) {
this.eno = eno;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return this.salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
HibernateSessionFactory.java
package info.inetsolv;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
client program to insert record into DB
InsertEmprecord.java
package info.inetsolv;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertEmprecord {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Emp e = new Emp();
e.setEno(6);
e.setName("six");
e.setSalary(1234d);
hsession.persist(e);
tx.commit();
hsession.close();
sf.close();
}
}
And below is my hibernate mapping file
Emp.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="info.inetsolv.Emp" table="EMP" schema="HIB">
<id name="eno" type="java.lang.Integer">
<column name="ENO" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="10" />
</property>
<property name="salary" type="java.lang.Double">
<column name="SALARY" precision="10" />
</property>
</class>
</hibernate-mapping>
AND below is my hibernate configuration file
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="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<property name="connection.username">hib</property>
<property name="connection.password">abc</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="myeclipse.connection.profile">
my oracle drive
</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
You didn't configure mapping for the object Emp. The configuration file hibernate.cfg.xml should contain the mapping to the resource Emp.hbm.xml.
<mapping resource="info/inetsolv/Emp.hbm.xml"/>
I had similar problem for a simple Console application trying to use Hibernate. The solution I arrived to make the add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.mg.learning.spring.orm"/> <--- this SOLVED!
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
#Sandhu Santakumar , answer is absolutely right.
Just adding the reason behind this.
By default the JBoss hibernate reverse engineering tool maps class inside the mapping tab but resource attribute is the required attribute that hibernate.cfg.xml should have.
class attribute is optional.
e.g. if your mapping is like this
resource is mandatory attribute and class is optional attribute.
Hope this additional information helps.
I get tired of this for a long time. I do not know what caused this error. Here are my files:
Uzytkownik.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="Uzytkownik" table="uzytkownicy">
<id column="id" name="id" type="int"/>
<property column="login" generated="never" lazy="false" name="login" type="string"/>
<property column="haslo" generated="never" lazy="false" name="haslo" type="string"/>
</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">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/sprawozdania</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<mapping resource="com/vaannila/uzytkownik/Uzytkownik.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I use mysql 5.5.
I get the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.<clinit>(HibernateUtil.java:14)
at com.vaannila.uzytkownik.Main.saveUzyt(Main.java:22)
at com.vaannila.uzytkownik.Main.main(Main.java:16)
Caused by: org.hibernate.MappingException: entity class not found: Uzytkownik
This are my classes:
main.java
package com.vaannila.uzytkownik;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.persistence.Entity;
import com.vaannila.util.HibernateUtil;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
Main obj = new Main();
String uzytkownikLogin = obj.saveUzyt("Adam", "Malysz");
}
public String saveUzyt(String login, String haslo){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
String uzytLog = null;
try {
transaction = session.beginTransaction();
Uzytkownik uzyt = new Uzytkownik();
uzyt.setLogin(login);
uzyt.setHaslo(haslo);
uzytLog = (String) session.save(uzyt);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return uzytLog;
}
}
Uzytkownik.java:
package com.vaannila.uzytkownik;
// default package
// Generated 2011-07-14 13:39:18 by Hibernate Tools 3.4.0.CR1
/**
* Uzytkownik generated by hbm2java
*/
public class Uzytkownik implements java.io.Serializable {
private int id;
private String login;
private String haslo;
public Uzytkownik() {
}
public Uzytkownik(int id) {
this.id = id;
}
public Uzytkownik(int id, String login, String haslo) {
this.id = id;
this.login = login;
this.haslo = haslo;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
public String getHaslo() {
return this.haslo;
}
public void setHaslo(String haslo) {
this.haslo = haslo;
}
}
HibernateUtil.java:
package com.vaannila.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Maybe your mapping file is not complete but other wise it should be:
<class name="com.vaannila.uzytkownik.Uzytkownik" table="uzytkownicy">
=> need to set fully qualified class name (with package)
I think it makes sense to specify full-qualified entity class name:
<class name="com.vaannila.uzytkownik.Uzytkownik" table="uzytkownicy">
Don't forget to mention your class using as a entity classes in hibernate configeration file using the mapping tag !!
Example:
<session-factory>
//database configeration goes here
<mapping class="org.fbis.models.Form3A"/>
</session-factory>
Stijn Geukens answers right,but I want to point out more information about this question.
There are two reasons I know causing this problem: entity class not found
First, As Stijn Geukens answers, Your Hibernate mapping is not right, the value of name attribute for the tag class should be the Java class with package ahead.
Second, if you have boolean filed in your Java class, this field can't start with is.Otherwise, the hibernate throws an exception getter method is not found... when run by Java Debug mode or Run mode.But when it comes to web project and you run your project as Server Application,the message becomes entity class not found.It made me puzzled for a long time.So do not name your boolean field with is ahead.