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 :-)
Related
how to resolve this exception... please help me...
while I am executing this simple hibernate programme. I am getting this exception :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]
mapping file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-mapping>
<class name = "Student" table = "STUDENT" >
<meta attribute="Class description">
This contains Student details.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="SNAME" type="String"/>
<property name="mNo" column="MNO" type="String"/>
<property name="marks" column="MARKS" type="String"/>
</class>
configuration file:
<?xml version = "1.0" encoding = "utf-8"?>
<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/firsthibernate</property>
<property name="hibernate.connection.user">root</property>
<property name="hibernate.connection.password">asdf</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
Pojo class:
public class Student {
private int id;
private String name;
private String mNo;
private String marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getmNo() {
return mNo;
}
public void setmNo(String mNo) {
this.mNo = mNo;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
marks = marks;
}
}
Test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DemoStudent {
public static void main(String[] args) {
Student st=new Student();
st.setId(1);
st.setName("Amit");
st.setmNo("8927070972");
st.setMarks("98%");
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
tr.begin();
s.save(st);
tr.commit();
}
}
Thanks in advance... while I am executing this simple hibernate programme. I am getting this please help me where I am doing mistake in this programme.
In hibernate mapping file use type as string instead of String.
<property name="name" column="SNAME"
type="string"/>
I'm trying to learn Hibernate using MySQL built-in database named world. It has three tables called city, country and countrylanguage. What I'm trying to do is execute SQL statement SELECT * FROM world.city;. When I run my project I'm getting error
org.hibernate.hql.internal.ast.QuerySyntaxException: City is not mapped [from City]
I'm using IntelliJ IDEA and Hibernate 5.2.8.
I created mapping xml file like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="pl.hibernatePackage">
<class name="City" table="city">
<id name="id" column="ID" type="int">
<generator class="native"/>
</id>
<property name="name" column="Name" type="string"/>
<property name="countryCode" column="CountryCode" type="string"/>
<property name="district" column="District" type="string"/>
<property name="population" column="Population" type="int"/>
</class>
</hibernate-mapping>
City.java is presented below:
public class City
{
private Integer id;
private String name;
private String countryCode;
private String district;
private Integer population;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
}
I'm creating session in HibernateUtil.java
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
standardServiceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Configuration file
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping resource="pl/hibernatePackage/City.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<City> cities = session.createQuery("from City").list();
for(City c : cities) {
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
}
EDIT Full error list
EDIT 2
javac result
I have done some testing and i made it work by using the fully qualified class name:
session.createQuery("from pl.hibernatePackage.City")
Now this is only a workaround without touching your config..
After digging deeper i found out that since hibernate version 5.x, there is a different strategy for building the sessionFactory.
I made your example work by implementing sessionFactory as follows:
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.getMetadataBuilder()
.build();
return configuration.buildSessionFactory(serviceRegistry);
This is explained with example here: jboss documentation (point 2.4)
Thanks to Maciej's answer and help of other guys I managed to get my example to work by modifying code and cleaning it up a little. I also found out that mapping DB with xml file is outdated so I modifiied properly CityEntity class. Final code:
Main.java
import org.hibernate.Session;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSession();
session.beginTransaction();
List<CityEntity> cities = session.createQuery("from CityEntity").list();
for(CityEntity c : cities)
{
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.close();
}
}
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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of mapped classes -->
<mapping class="CityEntity"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Session getSession()
{
return sessionFactory.openSession();
}
public static void close()
{
sessionFactory.close();
}
}
CityEntity.java
import javax.persistence.*;
#Entity
#Table(name = "city", schema = "world")
public class CityEntity
{
private int id;
private String name;
private String countryCode;
private String district;
private int population;
#Basic
#Column(name = "CountryCode")
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Id
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "District")
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
#Basic
#Column(name = "Population")
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
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();
}
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.