java.lang.NullPointerException in sessionfactory hibernate - java

I'm trying to build an application using hibernate. The thing is, sessionFactory can't open a session because there is a NullPointerException at Session session = sessionFactory.openSession(); and that's why at myAccount.addElement("August", 50000, 14000, 10000, 10000, 16000); too.
Main class
package myaccount1;
import myaccount.entity1.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.List;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class MyAccount {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static void main(String[] args) {
MyAccount myAccount = new MyAccount();
System.out.println("Adding an element");
myAccount.addElement("August", 50000, 14000, 10000, 10000, 16000);
myAccount.addElement("September", 50000, 14000, 10000, 10000, 16000);
System.out.println("List of elements");
}
public void addElement(String mounth, int salary, int must_save_for_rent, int must_save_for_education, int must_save, int balance) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
MyAccountEntity element = new MyAccountEntity(mounth, salary, must_save_for_rent, must_save_for_education, must_save, balance);
session.save(element);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
e.printStackTrace();
}
e.printStackTrace();
} finally {
session.close();
}
}
}
Configuration 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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/app?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">sopromat</property>
<mapping class="myaccount.entity1.MyAccountEntity.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil class
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory =
buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
//Use config file path explicitly
//configuration.configure("hibernate/hibernate.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory "
+ "creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Mapping 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="myaccount.entity1.MyAccountEntity" table="myaccount">
<id name="id" type="int" column="id">
<generator class="auto_increment"/>
</id>
<property name="mounth" column="mounth" type="string"/>
<property name="salary" column="salary" type="int"/>
<property name="must_save_for_rent" column="must_save_for_rent" type="int"/>
<property name="must_save_for_education" column="must_save_for_education" type="int"/>
<property name="must_save" column="must_save" type="int"/>
<property name="balance" column="balance" type="int"/>
</class>
</hibernate-mapping>
Project structure
enter image description here
What's wrong?
Please help, i don't know what to do.

Related

Why am I facing this error? - java.lang.ExceptionInInitializerError

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?

Exception in thread "main" org.hibernate.MappingException

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.

Hibernate 5: sessionFactory is null

Im getting a null value for sessionFactory variable at this line:
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
This is the whole class:
import javax.imageio.spi.ServiceRegistry;
import javax.transaction.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import ch.makery.model.Employee;
public class HelloWorld {
protected void setUp() throws Exception {
}
public static void main(String[] args) {
SessionFactory sessionFactory = null;
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
Session session = sessionFactory.openSession();
//employee = new Employee();
session.beginTransaction();
session.save(new Employee());
session.getTransaction().commit();
session.close();
}
}
This is my Hibernate related files:
<?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.password">manolete</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/employee</property>
<property name="hibernate.connection.username">root</property>
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="src/ch/makery/model/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?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 14-dic-2015 21:00:04 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="ch.makery.model.Employee" table="EMPLOYEE">
<id name="id" type="int">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="firstName" type="java.lang.String">
<column name="FIRSTNAME" />
</property>
<property name="lastName" type="java.lang.String">
<column name="LASTNAME" />
</property>
</class>
</hibernate-mapping>
package ch.makery.model;
public class Employee {
private int id;
private String firstName,lastName;
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;
}
}
Im not using Spring since Im just creating a desktop application.
The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above try to write the configuration like this:
Configuration configuration = new Configuration().configure();
configuration.configure("your_path_hibernate_.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
When I updated my Hibernate code from v4.1.8 to v5.0.6 I too had a problem with my SessionFactory instance being null. By printing the stack trace I was able to figure out that I needed to include the optional c3p0 jars in my build path.
My first suggestion would be to print the stack trace directly from your catch block. The trace will provide a good starting point on your way toward resolution. So your catch block would look like:
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
e.printStackTrace();
}
However, I notice that you don't have a hibernate.dialect property defined in your configuration file. While this property is not mandatory the Hibernate User Guide notes that there may be "some reason" hibernate is not able to determine which dialect you are using. My second suggestion would be to define your database dialect directly in your configuration file with the hibernate.dialect setting.
Since your original configuration file post suggests that you are making use of the MySQL database dialect, try adding in this dialect property node to the session-factory node:
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
If you are using MySQL 5.x then use
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
Make sure that the optional c3p0 jars are in your build path.
Best of luck!
private static SessionFactory sessionFactory = createSessionFactory();
private static SessionFactory createSessionFactory() {
if (sessionFactory == null) {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() .configure("hibernate.cfg.xml").build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
sessionFactory.getCurrentSession().close();
}

Hibernate Mapping Exception:Unknown Mapping Entity :Theme

I want to map class Themes to themes table.
Themes.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
public class Themes
{
private int id;
private String theme;
private int orderInfo;
public Themes(String theme,int order_info)
{
System.out.println("OK");
this.theme=theme;
this.orderInfo=order_info;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getTheme()
{
return theme;
}
public void setTheme(String theme)
{
this.theme=theme;
}
public int getOrder()
{
return orderInfo;
}
public void setOrder(int order_info)
{
this.orderInfo=order_info;
}
}
Themes.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="Themes" table="themes">
<meta attribute="class-description">
This class contains theme details.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="text" column="text" type="string"/>
<property name="orderInfo" column="order_info" type="int"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"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>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/content_templating_data
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
</property>
<!-- List of XML mapping files -->
<mapping resource="themes.hbm.xml"/>
<mapping resource="patterns.hbm.xml"/>
<mapping resource="filler.hbm.xml"/>
<mapping resource="sentences.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I a reading the contents from a csv file and i want it to insert in a databse using the following code.
ManageData.java
import java.io.*;
import org.apache.log4j.BasicConfigurator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageData {
private static SessionFactory factory;
private static String csvfile="C:\\Users\\ANJANEY\\IdeaProjects\\hiveminds\\src\\file.csv";
private static String line="";
private static String splitby=",";
private static BufferedReader br=null;
private static SessionFactory getSessionFactory() {
// create configuration using hibernate API
Configuration configuration = new Configuration();
configuration.setProperty("connection.driver_class",
"com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url",
"jdbc:mysql://localhost:3306/content_templating_data");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "");
return configuration.buildSessionFactory();
}
public static void main(String args[])throws IOException {
int count=0;
try
{
factory=getSessionFactory();
System.out.println("Factory Object created...");
}
catch (Throwable ex)
{
System.out.println("Failed to create Session Factory Object " + ex);
//throw new ExceptionInInitializerError();
}
try {
int order_info;
br = new BufferedReader(new FileReader(csvfile));
ManageData MD = new ManageData();
line = br.readLine();
int length=0;
while ((line = br.readLine()) != null) {
count++;
String[] str = line.split(splitby);
length=str.length;
order_info = Integer.parseInt(str[2]);
//Adding theme details in the theme table
Integer themeID = MD.addTheme(str[1], order_info);
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done "+count);
}
//Method to add in theme table
public Integer addTheme(String theme,int order_info){
Session session = factory.openSession();
Transaction tx = null;
Integer themeID = new Integer(0);
try{
tx = session.beginTransaction();
Themes th=new Themes(theme,order_info);
themeID = (Integer) session.save(th);
System.out.println("OKAY");
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return themeID;
}
I am getting the following error
Exception in thread "main" org.hibernate.MappingException: Unknown entity: Themes
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1485)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:120)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:713)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:701)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:697)
at ManageData.addTheme(ManageData.java:114)
at ManageData.main(ManageData.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
The mistake is you should add your package name into the Themes.hbm.xml like <class name="my.package.Themes" table="themes"> than it works.
Another problem is that your mapping is not equivalent to your getter & setter and fields:
<property name="text" column="text" type="string"/>
<property name="orderInfo" column="order_info" type="int"/>
text does not exists change it to theme. And the orderInfo getter/setter should looks like:
public int getOrderInfo() {
return orderInfo;
}
public void setOrderInfo(int order_info) {
this.orderInfo = order_info;
}
Than the theme class works for me.
€dit: You can use something like that, too.
<hibernate-mapping package="my.package">
<class name="Themes" table="themes">
....
</hibernate-mapping>

Exception in thread "main" org.hibernate.MappingException: Unknown entity:

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.

Categories