I'm learning hibernate and when I run the following program, I get this message :
Hibernate: insert into contact (firstname, lastname, email, id) values (?, ?, ?, ?) but when I check the table, nothing seems to be inserted. What's the problem here ? Clearly the statement value field is null but why?
I have the following POJO:
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
/**
* #return Email
*/
public String getEmail() {
return email;
}
/**
* #return First Name
*/
public String getFirstName() {
return firstName;
}
/**
* #return Last name
*/
public String getLastName() {
return lastName;
}
/**
* #param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}
/**
* #param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}
/**
* #param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}
/**
* #return ID Returns ID
*/
public long getId() {
return id;
}
/**
* #param l Sets the ID
*/
public void setId(long l) {
id = l;
}
}
and below are my hibernate config and hbm files:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/aneesh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.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">
<hibernate-mapping>
<class name="Contact" table="contact">
<id name="id" column="id" >
<generator class="assigned"/>
</id>
<property name="firstName" >
<column name="firstname" />
</property>
<property name="lastName">
<column name="lastname"/>
</property>
<property name="email" >
<column name="email"/>
</property>
</class>
</hibernate-mapping>
and here is my code to insert :
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
public class HSession {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionGet = new Configuration().configure().buildSessionFactory();
session = sessionGet.openSession();
Contact contact = new Contact();
contact.setFirstName("xyz");
contact.setLastName("zyx");
contact.setEmail("x#xmail.com");
contact.setId(20);
session.save(contact);
}finally{
// Actual contact insertion will happen at this step
try {
session.flush();
session.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You forgot the begin and commit the transaction.
session = sessionGet.openSession();
**Transaction tx= session.beginTransaction();**
Contact contact = new Contact();
contact.setFirstName("xyz");
contact.setLastName("zyx");
contact.setEmail("x#xmail.com");
contact.setId(20);
session.save(contact);
**tx.commit();**
Before you are saving the object you have to get the transaction and after saving the object you have to commit the transaction.
Transaction tx = session.beginTransaction();
session.save(contact);
tx.commit();
Use transaction in save.
session.getTransaction().begin();
session.save(contact);
session.getTransaction().commit();
you should do a commit for the insert to be reflected in database
try
session.getTransaction().commit();
after your
session.save(contact);
Related
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.
This question already has answers here:
Maven Run Project
(6 answers)
Closed 7 years ago.
In Eclipse, I have been building a simple Hibernate+Spring+MySQL+Maven project recently.I am stuck at the stage of database&java connection.When I run the project, it gives the the following error:
Exception in thread "main" org.hibernate.MappingException: Unable to load class [ src/main/java/com.hibernate.data/Person] declared in Hibernate configuration <mapping/> entry
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2279)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2227)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2207)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2160)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
at com.test.Main.main(Main.java:17)
Caused by: java.lang.ClassNotFoundException:src/main/java/com.hibernate.data/Person
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2276)
... 5 more
The main class:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.hibernate.data.Person;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction, if you would like save your instances, your calling of save must be associated with a transaction
Transaction tx = session.getTransaction();
// Create person
Person newPerson = new Person();
newPerson.setFirstName("Peter");
newPerson.setLastName("Jackson");
newPerson.setGender("Male");
newPerson.setAge(30);
//Save
session.save(newPerson);
session.flush();
tx.commit();
session.close();
/*
#SuppressWarnings("deprecation")
SessionFactory sf = new Configuration().configure().buildSessionFactory();
System.out.println("CFG and hbm files loaded successfully.");
Session session = sf.openSession();
session.beginTransaction();
System.out.println("Transaction began");
*/
}
}
hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="Person" lazy="false" name="com.hibernate.data.Person" >
<id column="PERSON_ID" type="int" name="id" >
<generator class="increment"/>
</id>
<property name="firstName" column="PERSON_FIRSTNAME" type="string" />
<property name="lastName" column="PERSON_LASTNAME" type="string" />
<property name="gender" column="PERSON_GENDER" type="string" />
<property name="age" column="PERSON_AGE" type="int" />
</class>
hibernate.cfg.xml 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>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
<property name='connection.username'>root</property>
<property name='connection.password'>root</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify session context -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Referring Mapping File -->
<mapping resource="domain-classes.hbm.xml"/>
<mapping class="src/main/java/com.hibernate.data/Person"/>
</session-factory>
</hibernate-configuration>
Person.java:
package com.hibernate.data;
public class Person {
private int id;
private String firstName;
private String lastName;
private String gender;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
What is wrong here?
EDIT:
I modified pom.xml file as maven-exec plugin requires:
Additionally, final project structure is as follows:
but still, it gives the same error.What am I doing wrong?
i think:
<mapping class="src/main/java/com.hibernate.data/Person"/>
must be:
<mapping class="com.hibernate.data.Person"/>
also be sure that where is your hbm.xml file?if it is in com package you should write resource like this:
<mapping resource="com/domain-classes.hbm.xml"/>
change
<mapping class="src/main/java/com.hibernate.data/Person"/>
to
<mapping class="com.hibernate.data.Person"/>
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.
The following code is for insert delete and update data in mysql database table name is student and i created a view using this student table can i perform insert update delete operations on this view if possible suggest me how
This code to retrieve object
package roseindia.tutorial.hibernate;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExam {
public static void main(String[] args)
{
Session session = null;
try{
SessionFactory sessionFactory =newConfiguration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transacton =session.beginTransaction();
System.out.println("Inserting Record");
Contact contact = new Contact();
//contact.setId(1);
contact.setFirstName("Vikas");
contact.setLastName("Kumar");
contact.setEmail("vikas#gmail.com");
session.save(contact);
//session.update(contact);
//session.delete(contact);
transacton.commit();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
code for persistence class
package roseindia.tutorial.hibernate;
public class Contact {
private String firstName;
private String lastName;
private String email;
private int id;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String string) {
email = string;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
public int getId() {
return id;
}
public void setId(int i) {
id = i;
}
}
mapping class
<hibernate-mapping>
<class name="roseindia.tutorial.hibernate.Contact" table="STUDENT">
<id name="id" type="int" column="ID" >
<generator class="increment"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
configuration class
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.161/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
So Im writing a test application. I want to save collections within every collected class. Each collected class has a unieq list of Data. I cant save the data classes.
the error I am getting
ERROR: Referential integrity constraint violation: "FK2EEFAAF2485486: PUBLIC.DATA FOREIGN KEY(NUMBER) REFERENCES PUBLIC.COLLECTED(KEY) (4)"; SQL statement: insert into data (number, data) values (null, ?) [23506-170]
Main class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
/**
*
* #author ivan
*/
public class HibernateCollectionTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Session session = Util.getSessionFactory().openSession();
Collected temp = new Collected();
temp.setDescription("test");
List<Data> local= new ArrayList<>();
for(int i=0;i<5;i++)
{
Data test = new Data();
test.setData("Data"+i);
local.add(test);
}
temp.setDatas(local);
session.beginTransaction();
session.save(temp);
session.getTransaction().commit();
Criteria crit = session.createCriteria(Collected.class);
List<Collected> dump =crit.list();
for(int i = 0 ; i < dump.size();i++)
{
System.out.println(dump.get(i).getKey()+" key "+dump.get(i).getDescription() +" describe ");
System.out.println("Size of collection is "+dump.get(i).getDatas().size());
for(int n=0;n<dump.get(i).getDatas().size();n++)
{
System.out.println(dump.get(i).getDatas().get(n).getData());
}
}
//session.flush();
}
}
The persistent class :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author ivan
*/
public class Collected
{
private String description;
private int key;
private List<Data> datas = new ArrayList<>();
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the key
*/
public int getKey() {
return key;
}
/**
* #param key the key to set
*/
public void setKey(int key) {
this.key = key;
}
/**
* #return the datas
*/
public List<Data> getDatas() {
return datas;
}
/**
* #param datas the datas to set
*/
public void setDatas(List<Data> datas) {
this.datas = datas;
}
}
Data class inside the collection :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
/**
*
* #author ivan
*/
public class Data
{
private int number;
private String data;
/**
* #return the number
*/
public int getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
/**
* #return the data
*/
public String getData() {
return data;
}
/**
* #param data the data to set
*/
public void setData(String data) {
this.data = data;
}
}
Hibernate Mappings :
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">
jdbc:h2:testdatabase
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="Collected.hbm.xml"/>
<mapping resource="Data.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Data.hbm
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatecollectiontest">
<class name="Data" table="data">
<id name="number" column="number" type="java.lang.Integer">
<generator class="native"/>
</id>
<property column="data" name="data" type="java.lang.String"/>
</class>
</hibernate-mapping>
Collected.hbm
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatecollectiontest">
<class name="Collected" table="collected">
<id name="key" column="key" type="java.lang.Integer">
<generator class="native"/>
</id>
<property column="description" name="description" type="java.lang.String"/>
<list name="datas" table="data" lazy="false" cascade="all">
<key column="number"/>
<list-index column="sortOrder"/>
<one-to-many class="hibernatecollectiontest.Data"/>
</list>
</class>
</hibernate-mapping>
To start with.,
Transaction is not getting committed.,
//session.getTransaction().commit();
Above line is commented in the code base.,