hibhernate and Mysql connection - java

package com.simpleprogrammer;
import org.hibernate.Session;
public class Program {
public static void main(String[] args) {
System.out.println("HEY");
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("pallavi");
user.setGoal(100);
session.getTransaction().commit();
session.close();
HibernateUtilities.getSessionFactory().close();
}
User.java
package com.simpleprogrammer;
public class User {
private int id;
private String name;
private int total;
private int goal;
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 int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
}
HibernateUtilities.java
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static StandardServiceRegistry serviceRegistry;
static{
try{
Configuration configuration = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch(HibernateException exception){
System.out.println("Problem creating session factory");
exception.printStackTrace();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/*
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateUtilities.sessionFactory = sessionFactory;
} */
}
Hibernate config file :-----------------
<?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.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.generate_statistics">false</property>
<mapping resource="com/simpleprogrammer/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User mapping file-----------------------
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 1 May, 2017 12:09:45 PM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="com.simpleprogrammer.User" table="USERS">
<id name="id" type="int">
<column name="ID" />
<generator class="identity" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="total" type="int">
<column name="TOTAL" />
</property>
<property name="goal" type="int">
<column name="GOAL" />
</property>
</class>
</hibernate-mapping>
Everything is working fine but data is not getting stored in database, i dont understand what is wrong!

You create the User entity, but you do not tell the persistence provider to actually manage it and eventually physically store it in the database:
User user = new User();
user.setName("pallavi");
user.setGoal(100);
session.persist(user);
Alternatively you can use save method.
This is the case when creating a new entity. If you were to update an existing entity, which you queries within the same transaction, then you would not need to explicitly call the update or merge operation as the persistence provider would do that for you implicitly on transaction commit.

Related

Data is not inserting in the specified column

Hi I have a class Vehicle is the Parent Class and Two Wheeler and Four Wheeler are the Child Classes that extends parent class.
The problem is when I'm inserting data to my rto(id,name,vehicle_type,steeringHandle,steeringWheel) table in database it is inserting the assigned data for the TwoWheeler but for FourWheeler it is inserting the data for the method present in Parent Class but when I'm calling a method from child class(FourWheeler(setsteeringWheel)) it's not updating the specified data in the
steeringWheel column. I'm adding the screen shot of my table.
Vehicle Class
`
package hibernate_discriminator;
import java.io.Serializable;
public class Vehicle implements Serializable {
private int id;
private String name;
public Vehicle(){
}
public int getId(){
return id;
}
public void setId(int id){
this.id= id;
}
public void setName(String name){
this.name= name;
}
public String getName(){
return name;
}
}
TwoWheeler Class
`package hibernate_discriminator;
public class TwoWheeler extends Vehicle{
private String steeringHandle;
public TwoWheeler(){
}
public void setsteeringHandle(String handle){
this.steeringHandle= handle;
}
public String getsteeringHandle(){
return steeringHandle;
}
}
`
FourWheeler Class
package hibernate_discriminator;
public class FourWheeler extends Vehicle {
private String steeringWheel;
public FourWheeler(){
}
public void setsteeringWheel(String wheel){
this.steeringWheel= steeringWheel;
}
public String getsteeringWheel(){
return steeringWheel;
}
}
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="hibernate_discriminator.Vehicle" table="rto" discriminator-value="vehicle">
<id name="id" column="id" type="integer">
<generator class="increment"></generator>
</id>
<discriminator column="vehicle_type" type="string"></discriminator>
<property name="name" column="name" type="string"></property>
<subclass name="hibernate_discriminator.TwoWheeler" extends="Vehicle" discriminator-value="Bike">
<property name="steeringHandle" column="steeringHandle" type="string"></property>
</subclass>
<subclass name="hibernate_discriminator.FourWheeler" extends="Vehicle" discriminator-value="Car">
<property name="steeringWheel" column="steeringWheel" type="string"></property>
</subclass>
</class>
</hibernate-mapping>
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/hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">ankita</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<mapping resource="resources/Vehicle.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main Class
public class Main {
public static void main(String[] args){
Configuration cfg= new Configuration();
cfg.configure("/resources/Config.cfg.xml");
SessionFactory sf= cfg.buildSessionFactory();
Session s= sf.openSession();
Transaction tx= s.beginTransaction();
Vehicle v= new Vehicle();
v.setName("Vehicle");
TwoWheeler tw= new TwoWheeler();
tw.setName("CBR");
tw.setsteeringHandle("CBR Handle");
FourWheeler fw= new FourWheeler();
fw.setName("Audi A4");
fw.setsteeringWheel("Audi a7 Wheel");
s.save(v);
s.save(tw);
s.save(fw);
s.flush();
tx.commit();
}
}
Adding my database scrrenshot
FourWheeler Class
public class Main {
public static void main(String[] args){
Configuration cfg= new Configuration();
cfg.configure("/resources/Config.cfg.xml");
SessionFactory sf= cfg.buildSessionFactory();
Session s= sf.openSession();
Transaction tx= s.beginTransaction();
Vehicle v= new Vehicle();
v.setName("Vehicle");
TwoWheeler tw= new TwoWheeler();
tw.setName("CBR");
tw.setsteeringHandle("CBR Handle");
FourWheeler fw= new FourWheeler();
fw.setName("Audi A4");
fw.setsteeringWheel("Audi a7 Wheel");
s.save(v);
s.save(tw);
s.save(fw);
s.flush();
tx.commit();
}
}
I think your problem is here...
public void setsteeringWheel(String wheel){
this.steeringWheel= steeringWheel;
}
The method parameter is wheel, but you're assigning the value of steeringWheel. (You're assigning this.steeringWheel = steeringWheel, which means it will have the same value -- null -- after the call to setsteeringWheel().)
Problem is here
public void setsteeringWheel(String wheel){
this.steeringWheel= steeringWheel;
}
You are not using the passed parameter
this.steeringWheel= wheel;

Getting org.hibernate.MappingException: Unknown entity:

Yes, I have seen this question all over the place,but am still not able to figure out what is the issue with my code. Certainly am overlooking something, can't just tell what. I could certainly use a second eye.
Here's my POJO.
package hibernate;
public class User {
private int id;
private String name;
private int total;
private int goal;
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 int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
}
Below is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=test;</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">admin</property>
<mapping resource="hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Here's my User.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 Jan 18, 2016 12:10:00 AM by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="hibernate.User" table="USER">
<id name="id" type="int">
<column name="ID" />
<generator class="native" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="total" type="int">
<column name="TOTAL" />
</property>
<property name="goal" type="int">
<column name="GOAL" />
</property>
</class>
</hibernate-mapping>
Here's the main app putting the above together:
package hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class App {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
User user = new User();
user.setName("Joe");
user.setGoal(250);
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtility.getSessionFactory().close();
}
}
When i run the above, I get the exception below.
Jan 18, 2016 9:34:04 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
Exception in thread "main" org.hibernate.MappingException: Unknown entity: hibernate.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1520)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:679)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:666)
at hibernate.App.main(App.java:27)
I have seen many people having this issues,but still havent been able to figure out mine. Thanks a bunch for your help.
Your session factory configuration is incorrect for Hibernate 5. If you use Hibernate 5, you can create a session factory by this way
sessionFactory = new Configuration().configure().buildSessionFactory();
In the file User.hbm.xml you shouldn't use namespace
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
Use
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
instead
I think mistake is on this line:
<class name="hibernate.User" table="USER">
Change hibernate.User to User, it should help.

HIBERNATE4 org.hibernate.MappingException: Unknown entity

I'm learnig Hibernate4 and I have encountered this problem while trying the XML hibernate mapping.
I'm using eclipse and MySQL.
The error when I try to insert my object in the DB table:
org.hibernate.MappingException: Unknown entity:
com.hibernate.gestionproductos.modelo.Proveedores
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="sfBDHibernate">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bdhibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.hibernate.gestionproductos.modelo.Proveedores"/>
</session-factory>
</hibernate-configuration>
You can see the class Proveedores is mapped.
ProveedoresDAO.java:
package com.hibernate.gestionproductos.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.hibernate.gestionproductos.modelo.Proveedores;
public class ProveedoresDAO {
private SessionFactory getSessionFactory() {
configure hay que ponerle el path
Configuration configuracion = new Configuration().configure();
// HIBERNATE 4
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuracion.getProperties());
SessionFactory sf = configuracion.buildSessionFactory(builder.build());
return sf;
}
public void insertarProveedor(Proveedores prov) {
try {
SessionFactory sf = getSessionFactory();
Session sesion = sf.openSession();
org.hibernate.Transaction tx = sesion.beginTransaction();
sesion.save(prov);
tx.commit();
sesion.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<Proveedores> listarProveedores() {
try {
SessionFactory sf = getSessionFactory();
Session sesion = sf.openSession();
org.hibernate.Transaction tx = sesion.beginTransaction();
List<Proveedores> lista = sesion.createCriteria(Proveedores.class).list();
tx.commit();
sesion.close();
return lista;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
Proveedores.java:
package com.hibernate.gestionproductos.modelo;
public class Proveedores implements java.io.Serializable {
private Long idproveedores;
private String nombre;
private String contacto;
private String email;
private String telefono;
public Proveedores() {
}
public Proveedores(String nombre, String email) {
this.nombre = nombre;
this.email = email;
}
public Proveedores(String nombre, String contacto, String email, String telefono) {
this.nombre = nombre;
this.contacto = contacto;
this.email = email;
this.telefono = telefono;
}
public Long getIdproveedores() {
return this.idproveedores;
}
public void setIdproveedores(Long idproveedores) {
this.idproveedores = idproveedores;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getContacto() {
return this.contacto;
}
public void setContacto(String contacto) {
this.contacto = contacto;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
}
Proveedores.hbm.xml:
<?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>
<class name="com.hibernate.gestionproductos.modelo.Proveedores" table="proveedores" catalog="bdhibernate">
<id name="idproveedores" type="java.lang.Long">
<column name="idproveedores" />
<generator class="identity" />
</id>
<property name="nombre" type="string">
<column name="nombre" length="45" not-null="true" />
</property>
<property name="contacto" type="string">
<column name="contacto" length="45" />
</property>
<property name="email" type="string">
<column name="email" length="100" not-null="true" />
</property>
<property name="telefono" type="string">
<column name="telefono" length="12" />
</property>
</class>
</hibernate-mapping>
ConfiguracionXML.java:
package com.hibernate.gestionproductos.programa;
import java.util.List;
import com.hibernate.gestionproductos.dao.ProveedoresDAO;
import com.hibernate.gestionproductos.modelo.Proveedores;
public class ConfiguracionXML {
public static void main(String[] args) {
Proveedores prov = new Proveedores();
prov.setNombre("Proveedor 3");
prov.setContacto("Juan");
prov.setEmail("juan#proveedor3.com");
prov.setTelefono("632227612");
ProveedoresDAO dao = new ProveedoresDAO();
dao.insertarProveedor(prov);
System.out.println("Se ha insertado el proveedor");
List<Proveedores> proveedores = dao.listarProveedores();
System.out.println("Listado de Proveedores:\n");
for (Proveedores p : proveedores) {
System.out.println(p.getIdproveedores() + " - " + p.getNombre());
}
}
}
Here at dao.insertarProveedor(prov) it breaks:
org.hibernate.MappingException: Unknown entity:
com.hibernate.gestionproductos.modelo.Proveedores Se ha insertado el
proveedor at
org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at
org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1451)
.....
Anyone can help?
The issue is with the Hibernate.cfg.xml where you have mentioned
<mapping class="com.hibernate.gestionproductos.modelo.Proveedores"/>
This tells the Hibernate system to read this class as an entity, but the class itself doesn't has any such information. The above configuration(or class property of mapping tag) is used when you use annotations to describe an entity. In case you are using hbm XML to provide info about your entity, then use resource property of mapping tag in the following way -
<mapping resource="Proveedores.hbm.xml"/>
So replacing this line in the hbm xml doc will make Hibernate read the mapping definitions which you provided. As you didn't specify it now, you mapping info is not being read, and thus Hibernate doesn't know about this entity resulting in Unknown Entity.

`Unknown entity` Exception in hibernate

I am learning hibernate and I can't figure out why is this error popping up. I tried searching but I couldn't find a solution that helped me. I'd like to learn why am I getting this error.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1451)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at Program.main(Program.java:23)
Please help I have already wasted so many hours debugging this.
Here is my simple program,
Program.java
import org.hibernate.Session;
import com.simpleprogrammer.HibernateUtilities;
import com.simpleprogrammer.User;
public class Program {
/**
* #param args
* #throws ClassNotFoundException
* #throws SQLException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("Deepak");
user.setTotal(130);
user.setGoal(150);
session.save(user);
session.getTransaction().commit();
session.close();
}
}
HibernateUtilities.java
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtilities {
public static SessionFactory sessionFactory;
public static ServiceRegistry serviceRegistry;
static{
try{
Configuration configuation = new Configuration().configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuation.getProperties()).build();
sessionFactory = configuation.buildSessionFactory(serviceRegistry);
}catch(HibernateException e){
System.out.println("Error while creating Session Factory.");
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
User.java
package com.simpleprogrammer;
public class User {
private int id;
private String name;
private int total;
private int goal;
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 int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getGoal() {
return goal;
}
public void setGoal(int goal) {
this.goal = goal;
}
}
User.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 28, 2015 8:05:49 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.simpleprogrammer.User" table="users">
<id name="id" type="int">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<property name="total" type="int">
<column name="total" />
</property>
<property name="goal" type="int">
<column name="goal" />
</property>
</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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/simpleprogrammer/User.hbm.xml" />
</session-factory>
Actually I was using Hibernate 5 jars . But the tutorial is actually for Hibernate 4. When I used Hibernate 4 jars everything seems to working fine.
May be you don't need <mapping resource="com/simpleprogrammer/User.hbm.xml" />. Instead, try <mapping resource="User.hbm.xml" />

How to handle database null values in Hibernate Application?

I am getting " org.hibernate.PropertyAccessException" due to null values in my database table. How to handle the exception?
My files are
FetchTest.java
package com.raj.java.hiberanteDemos;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FetchTest {
public static void main(String[] args) {
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
SessionFactory factory=cfg.buildSessionFactory();
Session session1=factory.openSession();
Employee emp1=(Employee)session1.get(Employee.class,7839);
System.out.println(emp1.getEmpno()+" "+emp1.getEname()+" "+emp1.getSal());
session1.close();
Session session2=factory.openSession();
Employee emp2=(Employee)session2.load(Employee.class,7839);
System.out.println(emp2.getEmpno()+" "+emp2.getEname()+" "+emp2.getSal());
session2.close();
}
}
Employee.java
package com.raj.java.hiberanteDemos;
import java.sql.Date;
class Employee {
private int empno, mgr, deptnumber;
private String ename, job;
private double sal, comm;
private Date hiredate;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public int getDeptnumber() {
return deptnumber;
}
public void setDeptnumber(int deptnumber) {
this.deptnumber = deptnumber;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public double getComm() {
return comm;
}
public void setComm(double comm) {
this.comm = comm;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">someValidurl</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.show_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
<mapping resource="employee.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- <class name="com.javatpoint.mypackage.Employee" table="employee"> <id
name="empid"> <generator class="assigned"></generator> </id> <property name="firstName"></property>
<property name="lastName"></property> </class> -->
<class name="com.raj.java.hiberanteDemos.Employee" table="emp">
<id name="empno" type="int" column="EMPNO">
<generator class="increment" />
</id>
<property name="ename" type="java.lang.String" />
<property name="mgr" type="int" />
<property name="deptnumber" type="int" column="deptno" />
<property name="job" type="java.lang.String" />
<property name="sal" type="double" />
<property name="comm" type="double" />
<property name="hiredate" type="java.sql.Date" />
</class>
</hibernate-mapping>
When I ran this application I am getting below error message.
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select employee0_.EMPNO as EMPNO0_0_, employee0_.ename as ename0_0_, employee0_.mgr as mgr0_0_, employee0_.deptno as deptno0_0_, employee0_.job as job0_0_, employee0_.sal as sal0_0_, employee0_.comm as comm0_0_, employee0_.hiredate as hiredate0_0_ from emp employee0_ where employee0_.EMPNO=?
Exception in thread "main" org.hibernate.PropertyAccessException: exception setting property value with CGLIB (set hibernate.cglib.use_reflection_optimizer=false for more info) setter of com.raj.java.hiberanteDemos.Employee.setMgr
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:215)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:185)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3232)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:129)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1785)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:47)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:41)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2730)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:365)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:346)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:123)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:177)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:87)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:799)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:792)
at com.raj.java.hiberanteDemos.FetchTest.main(FetchTest.java:13)
Caused by: net.sf.cglib.beans.BulkBeanException
at com.raj.java.hiberanteDemos.Employee$$BulkBeanByCGLIB$$142cfd75.setPropertyValues(<generated>)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValuesWithOptimizer(PojoEntityTuplizer.java:212)
... 19 more
Caused by: java.lang.NullPointerException
... 21 more
my emp table data
when I update all the null values with 0 or some other values its working fine.
Please help me in solving the error without updating null values in database table.
Thanks in Advance,
Raj
I would personally recommend to actually "clean" the database values, maybe setting the column not nullable.
But if this can't be done, what you can do is modify your setters, so that it checks for null:
public void setComm(Double comm) {
if(null != comm){
this.comm = comm;
}else{
this.comm = 0;
}
}
hope this helps
Your mgr-Property is int, which does not allow null. Change it to Integer, which allows null. Or make a default value for your mgr column.
The best way to avoid Hibernate's attempts at setting null values to primitives is to use Wrapper classes (Integer, Long, Double...); and especially, if you need to tack on a column or 2 to an existing table. Auto-boxing is your friend.

Categories

Resources