How to fix "Duplicate property mapping" exception? - java

xml file to map a new table from my db but when I start the project I get a Duplicate property mapping error that I cannot understand and resolve. Here is my 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="session1">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/realestate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<mapping resource="entities/users.hbm.xml"/>
<mapping resource="entities/adminstration.hbm.xml"/>
<mapping resource="entities/seller.hbm.xml"/>
<mapping resource="entities/buyer.hbm.xml"/>
<mapping resource="entities/renter.hbm.xml"/>
<mapping resource="entities/leeser.hbm.xml"/>
<mapping resource="entities/house.hbm.xml"/>
<mapping resource="entities/userSellsHouse.hbm.xml"/>
<mapping resource="entities/userRentsHouse.hbm.xml"/>
<mapping resource="entities/messages.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The messages.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 name="entities.Message" table="MESSAGES" schema="realestate">
<id name="messageID" type="int">
<column name="messsageID" />
</id>
<property name="Date" type="java.lang.String">
<column name="Date" />
</property>
<property name="SenderID" type="java.lang.Integer">
<column name="Sender" />
</property>
<property name="ReceiverID" type="java.lang.Integer">
<column name="Receiver" />
</property>
<property name="Message" type="java.lang.String">
<column name="Message" />
</property>
<property name="Theme" type="java.lang.String">
<column name="Theme" />
</property>
</class>
</hibernate-mapping>
and the Message persisent class:
public class Message {
int MessageID;
int SenderID;
int ReceiverID;
String date;
String message;
String theme;
public int getMessageID() {
return MessageID;
}
public void setMessageID(int messageID) {
MessageID = messageID;
}
public int getSenderID() {
return SenderID;
}
public void setSenderID(int senderID) {
SenderID = senderID;
}
public int getReceiverID() {
return ReceiverID;
}
public void setReceiverID(int receiverID) {
ReceiverID = receiverID;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
}
and here's the error
...
Caused by: org.hibernate.MappingException: Duplicate property mapping of SenderID found in entities.Messages
at org.hibernate.mapping.PersistentClass.checkPropertyDuplication(PersistentClass.java:515)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:505)
at org.hibernate.mapping.RootClass.validate(RootClass.java:270)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1358)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1849)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at database.HibernateUtil.<clinit>(HibernateUtil.java:15)
... 46 more
Edit: I tried commenting out the <mapping resource="entities/messages.hbm.xml"/> from the cfg file and I still get the same error.
Edit2: The above is from a java EE project, I copied paste everything in a simle java project and it worked fine. Any suggestion?
Edit3: I added the final modifier to messages class to be sure that it cannot be inherited

Please go through the following link, this might help you...
Hibernate ORMHHH-2598
Mapping a collection of entities from two different classes with the same collection name results in duplicate backref property exception if collection keys are not null

Related

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.

Spring/Hibernate Write operations are not allowed in read-only mode

I've read some of other questions on the same topic, but in my case I'm not actually specifying anything. What makes me really confused is I have another call that works. I don't specify any transactions so I'm not sure why this is becoming a problem.
This is what happens when I try to use xssSave() (in the service class at the bottom), but sqlInject (also in the same class) works fine. As far as I can tell these operate identically except that one works and one doesn't.
If you want to view the full code and/or check it out yourself, it's available on GitHub (https://github.com/tenmilez/WebBilly).
Spring configuration (split into 3 files):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
<import resource="recipeasy-aspects.xml" />
-->
<import resource="webbilly-data.xml"/>
<import resource="webbilly-spring.xml"/>
<import resource="webbilly-service.xml"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order">
<value>0</value>
</property>
<property name="mappings">
<props>
<prop key="welcome.htm">welcomeController</prop>
<prop key="sqli.htm">SQLiController</prop>
<prop key="xss.htm">XssController</prop>
</props>
</property>
</bean>
<bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="method"/>
<property name="defaultMethodName" value="onInitPage"/>
</bean>
<bean id="welcomeController" class="com.webbilly.web.WelcomeController"/>
<bean id="SQLiController" class="com.webbilly.web.SQLiController">
<property name="methodNameResolver" ref="paramResolver"/>
<property name="sqliServices" ref="sqliServices"/>
</bean>
<bean id="XssController" class="com.webbilly.web.XssController">
<property name="methodNameResolver" ref="paramResolver"/>
<property name="sqliServices" ref="sqliServices"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sqliServices" class="com.webbilly.service.SQLiServices">
<property name="sqliDataDAO" ref="sqliDataDAOhibernate"/>
<!--
<property name="sqliDataDAO" ref="sqliDataDAOjdbc" />
<property name="sqliDataDAO" ref="sqliDataDAOhibernate" />
-->
<property name="xssDataDAO" ref="xssDataDAO"/>
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="jdbcDataSource"/>
<property name="mappingDirectoryLocations">
<value>classpath:/com/webbilly/dao/hibernate/hbm</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.dialect">${database.dialect}</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="genericDAO" class="com.webbilly.dao.hibernate.GenericDAO"
abstract="true">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="sqliDataDAOhibernate" parent="genericDAO">
<constructor-arg>
<value>com.webbilly.domain.SQLiData</value>
</constructor-arg>
</bean>
<bean id="xssDataDAO" parent="genericDAO">
<constructor-arg>
<value>com.webbilly.domain.XssData</value>
</constructor-arg>
</bean>
<bean id="sqliDataDAOjdbc" class="com.webbilly.dao.jdbc.SQLiDAO">
<property name="dataSource" ref="jdbcDataSource"/>
</bean>
<bean id="jdbcDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="connectionProperties">
<props>
<prop key="allowMultiQueries">true</prop>
</props>
</property>
</bean>
</beans>
My data objects (is there a name for these? Always referred to them as domain objects, but I'm not sure if that's widely accepted terminology).
package com.webbilly.domain;
/**
* Created by christopher on 12/12/14.
*/
public class XssData {
private int id;
private String userName;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.webbilly.domain;
/**
* Created by christopher on 12/3/14.
*/
public class SQLiData {
private String id;
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
The persistence layer
package com.webbilly.dao;
import java.util.Collection;
public interface IGenericDAO<T> {
void save(T t);
Collection<T> getAll();
T getById(int id);
void delete(int id);
}
package com.webbilly.dao.hibernate;
import com.webbilly.dao.IGenericDAO;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import java.util.Collection;
public class GenericDAO<T> extends HibernateDaoSupport implements IGenericDAO<T> {
/**
* ******************************************************
* ********* Accessors and private members ****************
* *******************************************************
*/
private Class<T> type;
public GenericDAO(Class<T> type) {
this.type = type;
}
public T getById(int id) {
return (T) getHibernateTemplate().get(type, id);
}
public Collection<T> getAll() {
return getHibernateTemplate().loadAll(type);
}
public void save(T t) {
getHibernateTemplate().saveOrUpdate(t);
}
public void delete(int id) {
getHibernateTemplate().delete(getById(id));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.webbilly.domain">
<class name="SQLiData" table="sqli">
<id column="id" name="id" type="int">
<generator class="increment"/>
</id>
<property name="value" type="string">
<column name="value"/>
</property>
</class>
</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.webbilly.domain">
<class name="XssData" table="xss">
<id column="id" name="id" type="int">
<generator class="increment"/>
</id>
<property name="userName" type="string">
<column name="user_name"/>
</property>
<property name="message" type="string">
<column name="message"/>
</property>
</class>
</hibernate-mapping>
The service layer (it really is just one class; my application is not that big yet).
package com.webbilly.service;
import com.webbilly.dao.IGenericDAO;
import com.webbilly.domain.SQLiData;
import com.webbilly.domain.XssData;
import java.util.Collection;
/**
* Created by christopher on 12/3/14.
*/
public class SQLiServices {
private IGenericDAO<SQLiData> sqliDataDAO;
private IGenericDAO<XssData> xssDataDAO;
public void sqlInject(String str) {
SQLiData sqliData = new SQLiData();
sqliData.setValue(str);
getSqliDataDAO().save(sqliData);
}
public void xssSave(XssData data) {
xssDataDAO.save(data);
}
public Collection<XssData> getAllPosts() {
return xssDataDAO.getAll();
}
public IGenericDAO<SQLiData> getSqliDataDAO() {
return sqliDataDAO;
}
public void setSqliDataDAO(IGenericDAO<SQLiData> sqliDataDAO) {
this.sqliDataDAO = sqliDataDAO;
}
public IGenericDAO<XssData> getXssDataDAO() {
return xssDataDAO;
}
public void setXssDataDAO(IGenericDAO<XssData> xssDataDAO) {
this.xssDataDAO = xssDataDAO;
}
}
HibernateTemplate doesn't manage transactions, you need a HibernateTransactionManager instead.
The write operations need to execute within the context of a transaction, so you need to also annotate you DAO or your services with #Transactional.

SQLGrammarException with Hibernated and oracle11g

I am merely trying to fetch a row of information from the CONTACTS table from my oracle sql database and I get this error :
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: la séquence n'existe pas (non existing sequence)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:776)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:897)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1034)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3867)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1502)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:116)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 12 more
Java Result: 1
My Contacts.hbm.xml 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="Contacts" table="CONTACTS">
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native"/>
</id>
<property name="nom" column="NOM" type="string" length="20"/>
<property name="prenom" column="PRENOM" type="string" length="20"/>
<property name="email" column="EMAIL" type="string" length="20"/>
<property name="salaire" column="SALAIRE" type="integer" length="12"/>
</class>
</hibernate-mapping>
My hibernate.cfg.xml 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.Oracle10gDialect
</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">
adresse...
</property>
<property name="hibernate.connection.username">
login
</property>
<property name="hibernate.connection.password">
psswrd
</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping class="Contacts" file="" jar="" package="" resource="Contacts.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and Contacts.java
import java.io.Serializable;
public class Contacts implements Serializable {
private int id_contact;
private String nom, prenom, email;
private float salaire;
public Contacts(){
}
public int getId_contact() {
return id_contact;
}
public void setId_contact(int id_contact) {
this.id_contact = id_contact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getSalaire() {
return salaire;
}
public void setSalaire(float salaire) {
this.salaire = salaire;
}
}
The error occurs when I call
session.save(contact1)
//contact1 has been using setters to populate its fields.
And my table on sqlplus look like this
Name Null? Type
----------------------------------------- -------- ----------------------------
IDCONTACT NOT NULL NUMBER(38)
NOM VARCHAR2(20)
PRENOM VARCHAR2(20)
EMAIL VARCHAR2(20)
SALAIRE NUMBER(12)
Thanks for taking a look.
I suppose you've created the table manually (without hibernate).
As you didn't declare the sequence name here
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native"/>
</id>
Hibernate tries to use a sequence named HIBERNATE_SEQUENCE
So you need to create HIBERNATE_SEQUENCE in your DB or define your sequence explicitly:
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native">
<param name="sequence">CONTACTS_SEQ</param>
</generator>
</id>

Doesn't save the data into data base. Hibernate and Spring connection

I connected data base with hibernate to my application with this settings:
hibernateContext.xml
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateUserDao" class="org.springframework.web.basepackage.HibernateUserDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
this is hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/fullproject</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="user.hbm.xml" />
</session-factory>
</hibernate-configuration>
this is user.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="org.springframework.web.basepackage.User" table="users">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="login" column="login"/>
<property name="password" column="password" />
<property name="email" column="email" />
</class>
</hibernate-mapping>
this is my user entity
public class User {
private int id;
private String login;
private String password;
private String email;
public User(){
}
public User(String login, String password, String email){
this.login = login;
this.password = password;
this.email = email;
}
public int getId(){
return id;
}
public String getLogin(){
return login;
}
public String getPassword(){
return password;
}
public String getEmail(){
return email;
}
public void setId(int id){
this.id = id;
}
public void setLogin(String login){
this.login = login;
}
public void setPassword(String password){
this.password = password;
}
public void setEmail(String email){
this.email = email;
}
}
when i try save db in this way "hibernateTemplate.save(user)' i catch in console this line
"Hibernate: insert into users (login, password, email) values (?, ?, ?)" and changes don't save into database. I tried in user.hbn.xml change generator class to "increment" because my id in data base table has AUTO INCREMENT parameter, but it doesn't work.
This sound like your transaction didn't get commit after update. When you call HibernateTemplate.update() it only update your persistent but doesn't actually to commit those changes. Remember to always conclude your transaction and save it before moving on.
Here are some resources on hibernate sessions and transactions that might help you with your current problem 1 and 2

Hibernate is not creating tables

I have been trying to make a table automatically with hibernate. Tried all the solutions given for the same question. Please have a look and point out what is wrong. I am using it with MySQL 5.6 version.
public class Tester
{
public static void main(String[] args)
{
SessionFactory factory = new Configuration().configure("com/hibernate.hbm.xml").buildSessionFactory();
System.out.println(factory.toString() + " - DONE");
}
}
Product class is :
public class Product
{
private String product;
private String productName;
public String getProduct()
{
return product;
}
public void setProduct(String product)
{
this.product = product;
}
public String getProductName()
{
return productName;
}
public void setProductName(String productName)
{
this.productName = productName;
}
}
My hbm file looks like this :
<?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 package="com">
<class name="Product" table="product_table">
<id name="product" column="product_id" type="java.lang.String" length="20" >
<generator class="assigned" />
</id>
<property name="productName" column="product_name" type="java.lang.String" length="50" not-null="true" />
</class>
</hibernate-mapping>
And hibernate.cfg.xml is given below -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/caching_hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="cache.providerclass">org.hibernate.NoCacheProvider</property>
<mapping resource="com/product.hbm.xml" />
</session-factory>
</hibernate-configuration>
Program shows no exception and runs normally..Thanks in advance

Categories

Resources