I'm trying get all the entries from Messages table using criteria
Criteria getCriteria = session.createCriteria(MessageAttributes.class);
List<MessageAttributes> unProcessedJcbMessagesList=getCriteria.list();
I'm getiing following exception when I'm trying run above criteria.
FieldId is the foreign key from AvailableFields(AvailableFieldsIs) table.
IllegalArgumentException occurred while calling setter for property [com.alu.jcb.model.MessageAttributes.fieldId (expected type = com.alu.jcb.model.AvailableFields)]; target = [com.alu.jcb.model.MessageAttributes#1cf3877], property value = [2]
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:123)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:713)
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:362)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4718)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:188)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at com.alu.jcb.messageProcessor.Test.main(Test.java:23)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:68)
... 17 more
Beans
MessageAttributes.java
public class MessageAttributes {
private long messageAttributeId=1L;
private AvailableFields fieldId;
private String value;
//getters and setters
}
AvailableFields.java
public class AvailableFields {
private long availableFieldsId=1L;
private Instance instance;
private String fieldDisplayName;
//getters and setters
}
HBM files
MessageAttributes.hbm.xml
<hibernate-mapping package="com.alu.jcb.model">
<class name="MessageAttributes" table="MESSAGE_ATTRIBUTES">
<id name="messageAttributeId" column="message_attribute_id" type="long">
<generator class="sequence" />
</id>
<many-to-one name="fieldId" class="com.alu.jcb.model.AvailableFields" fetch="select">
<column name="field_id" not-null="true" />
</many-to-one>
<property name="value" type="string" column="value" />
</class>
</hibernate-mapping>
AvailableFields.hbm.xml
<hibernate-mapping package="com.alu.jcb.model">
<class name="AvailableFields" table="AVAILABLE_FIELDS">
<id name="availableFieldsId" column="available_fields_id" type="java.lang.Long">
<generator class="sequence" />
</id>
<many-to-one name="instance" class="com.alu.jcb.model.Instance" fetch="select">
<column name="instance_id" not-null="true" />
</many-to-one>
<property name="fieldDisplayName" type="string" column="field_display_name" not-null="true"/>
</class>
</hibernate-mapping>
Please help me
The error means something wrong with setter of fieldId. It should be like this
public void setFieldId(AvailableFields fieldId) {
this.fieldId=fieldId;
}
but it seems in your case incorrect class (guess long) is used in the setter.
SQLQuery sqlquery=session.createSQLQuery(queryString);
sqlquery.addScalar("fieldId ", IntegerType.INSTANCE);
I was receiving this error of
IllegalArgumentException occurred while calling setter for property
Version (type expected is Long but received 0)
because instead of using
Query query = sess.createSQLQuery(sqlQueryStr).addEntity(instance.getClass().getName());
retval = query.list();
I was doing
Query query = sess.createSQLQuery(sqlQueryStr)
.setResultTransformer(Transformers.aliasToBean(instance.getClass()));
retval = query.list();
In case it helps anyone.
Related
I am trying one-to-one mapping from statusHistoryLogs to element in hibernate. I am new in Hibernate. I have added one to one mapping in element.hbm.xml also.
I am getting the following error: Duplicate property mapping of element found in com.ot.entry.members.StatusHistoryLog.
Please guide me, where I am going wrong. Please correct my code.
StatusHistoryLog.hbm.xml
<hibernate-mapping>
<class dynamic-insert="true" dynamic-update="true" name="com.ot.entry.members.StatusHistoryLog" table="status_history_logs">
<id name="id" type="long">
<column name="id" sql-type="integer"/>
<generator class="native"/>
</id>
<property name="element" length="11" column="element_id" type="integer" />
<property name="status" length="11" column="status_id" type="integer" />
<one-to-one name="element" class="com.ot.entry.members.Element" constrained="true"/>
<property name="period" type="period">
<column name="start_date" not-null="true"/>
<column name="end_date"/>
</property>
</class>
</hibernate-mapping>
element.hbm.xml
<hibernate-mapping>
<class dynamic-insert="true" dynamic-update="true" name="com.ot.entry.members.Element" abstract="true" table="members">
<id name="id" type="long">
<column name="id" sql-type="integer"/>
<generator class="native"/>
</id>
<discriminator column="subclass" type="string" length="1"/>
<property name="name" length="100" column="name" type="string" not-null="true"/>
<property name="creationDate" column="creation_date" type="calendar" not-null="true"/>
<many-to-one name="group" class="com.ot.entry.groups.Group">
<column name="group_id" not-null="true" sql-type="integer"/>
</many-to-one>
<property name="status" column="status" not-null="false" length="1">
<type name="com.paynet.utils.hibernate.StringValuedEnumType">
<param name="enumClassName">com.ot.entry.members.Element$Status</param>
</type>
</property>
<property name="email" length="100" column="email" type="string" index="ix_email"/>
<property name="notificationLanguage" column="notification_language" length="6" not-null="false">
<type name="com.paynet.utils.hibernate.StringValuedEnumType">
<param name="enumClassName">com.ot.entry.settings.LocalSettings$Language</param>
</type>
</property>
<one-to-one name="user" cascade="all" class="com.ot.entry.access.User" />
<one-to-one name="statusHistoryLogs" cascade="all" class="com.ot.entry.members.StatusHistoryLog" />
<bag name="groupHistoryLogs" cascade="delete" inverse="true" order-by="start_date">
<key>
<column name="element_id" sql-type="integer"/>
</key>
<one-to-many class="com.ot.entry.groups.GroupHistoryLog"/>
</class>
</hibernate-mapping>
StatusHistoryLog.java
public class StatusHistoryLog extends Entity {
private static final long serialVersionUID = 68407121216377438L;
private Element element;
private Status status;
private Period period;
public Element getElement() {
return element;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Period getPeriod() {
return period;
}
public void setElement(final Element element) {
this.element = element;
}
public void setPeriod(final Period period) {
this.period = period;
}
#Override
public String toString() {
String string = getId() + ": " + getStatus().getValue() + " - begin: " + period.getBegin();
if (period.getEnd() != null) {
string += " - end: " + period.getEnd();
}
return string;
}
}
<property name="element" length="11" column="element_id" type="integer" />
should be
<property name="elementId" length="11" column="element_id" type="integer" />
I have the following issue :
org.hibernate.NonUniqueObjectException:
A different object with the same identifier value was already associated with the session.
Strangely it does not occurs systematically.
Entity is loaded from database to Struts and set in HTTP Session.
Once modified it's send to business service for saving.
(sessionFactory.update, sessionFactory.save)
It should always have hibernate issue but the org.hibernate.NonUniqueObjectException occurs only some times (Don't know why)
Does any one have an explanation ?
I think about reload the object from hibernate session in my business service and copy data from entity object from Struts HTTP Session.
#Override
public boolean equals(Object autre) {
if (this == autre) {
return true;
}
if ((autre == null) || (autre.getClass() != this.getClass())) {
return false;
}
MouvementFinancier entite = (MouvementFinancier) autre;
if (pk == null || entite.pk == null) {
return false;
}
return pk.equals(entite.pk);
}
#Override
public int hashCode() {
if (pk == null) {
return super.hashCode();
}
return pk.hashCode();
}
Hibernate mapping
<class name="com.XXX.MouvementFinancier" table="MOUVEMENT_FINANCIER"
discriminator-value="0" abstract="true">
<id name="pk" type="integer" column="PK_MOUVEMENT_FINANCIER" unsaved-value="null">
<generator class="com.XXX.TableGenerator">
<param name="segment_value">MOUVEMENT_FINANCIER</param>
</generator>
</id>
<discriminator column="CLASSE" type="integer" />
<timestamp column="DATE_VERSION" name="version" unsaved-value="null" />
<property name="commentaire" column="COMMENTAIRE" />
...
<set name="actes" cascade="all,delete-orphan" fetch="select" sort="natural">
<key column="PK_MOUVEMENT_FINANCIER" not-null="true" />
<one-to-many class="com.p****.HistoriqueMouvement" />
</set>
<subclass name="com.XXX.Encaissement" discriminator-value="2">
<property name="purpose" column="NATURE_RECUPERATION" />
...
<many-to-one name="emetteur" column="PK_PERSONNE_EMETTEUR"
class="com.XXX.Personne" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="acteurEmetteur" column="PK_ACTEUR_EMETTEUR"
class="com.XXX.Acteur" cascade="none" fetch="join" lazy="false"/>
</subclass>
<subclass name="com.XXX.Reglement" discriminator-value="1">
<property name="dateAutorisation" type="timestamp" column="DATE_AUTORISATION" />
<property name="franchise" column="FRANCHISE" />
...
<many-to-one name="beneficiaire" column="PK_PERSONNE_BENEFICIAIRE"
class="com.XXX.Personne" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="acteurBeneficiaire" column="PK_ACTEUR_BENEFICIAIRE"
class="com.XXX.Acteur" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="adresseCourrierReglementBeneficiaire" column="PK_ADD_COUR_REG_BENEF"
class="com.XXX.AdresseCourrierReglement" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="destinataire" column="PK_PERSONNE_DESTINATAIRE"
class="com.XXX.Personne" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="acteurDestinataire" column="PK_ACTEUR_DESTINATAIRE"
class="com.XXX.Acteur" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="adresseCourrierReglementDestinataire" column="PK_ADD_COUR_REG_DEST"
class="com.XXX.AdresseCourrierReglement" cascade="none" fetch="join" lazy="false"/>
<many-to-one name="rib" column="PK_RIB" class="com.XXX.assureur.RIB"
cascade="all" fetch="select" />
<set name="ventilationDepenses" cascade="all,delete-orphan" fetch="select">
<key column="PK_MOUVEMENT_FINANCIER" not-null="true" />
<one-to-many class="com.XXX.Depense"/>
</set>
</subclass>
</class>
<class name="com.XXXX.Depense" table="VENTILATION_DEPENSES">
<id name="pk" type="integer" column="PK_VENTILATION_DEPENSE" unsaved-value="null">
<generator class="com.XXX.TableGenerator">
<param name="segment_value">VENTILATION_DEPENSES</param>
</generator>
</id>
<property name="nature" column="CODE_NATURE_DEPENSE" />
<property name="montant" column="MONTANT_DEPENSE" />
...
</class>
Issue has been solved by using Hiberante merge in DAO
But I still wonder why in most case there was no issue to send back a "detached" entity to service layer without using merge command or copy in an entity loaded from hibernate session.
// TODO : save (twice) replaced by 1 merge to avoid issue on detached object
// if we have any more pb on this, redo all : load payment from session and copy data in from dto.
session.merge(reglement);
Complete code
#Override
public void update...(...) {
if (logger.isDebugEnabled()) {
logger.debug("Updating a settlement");
}
Session session = sf.getCurrentSession();
final PartieFinanciere partieReglement = (PartieFinanciere) session.get(PartieFinanciere.class, pkPartieFinanciere);
if (partieReglement == null) {
throw new ExceptionPkEntiteInconnu(PartieFinanciere.class, pkPartieFinanciere);
}
// History : last movement amount to remove it on total amount
HistoriqueMouvement movementHistoryLast = reglement.getActes().stream().sorted((h1, h2) -> h2.compareTo(h1)).findFirst().orElse(null);
Double mouvementLastAmount = movementHistoryLast != null ? movementHistoryLast.getMontant() : 0;
// History : add movement modification in history
HistoriqueMouvement histo = new HistoriqueMouvement();
histo.setActe(...);
histo.setDate(...);
histo.setMontant(...);
.....
reglement.getActes().add(histo);
partieReglement.getMouvements().add(reglement);
// Recalculate total amount : remove previous movement amount, set movement modified amount
Double amountProvision = ofNullable(partieReglement.getTotalMouvements()).orElse(0.0).doubleValue() - mouvementLastAmount + reglement.getMontant();
partieReglement.setTotalMouvements(amountProvision);
if (logger.isDebugEnabled()) {
logger.debug("Updating total mouvement and suspens.");
}
mettreAJourTotalMouvementsEtSuspens(session, partieReglement);
ajouterActePartieFinanciere(gestionnaire, partieReglement, getHistoriquePartieActe(null, reglement.getType(), false), reglement.getMontant());
// TODO : save (twice) replaced by 1 merge to avoid issue on detached object
// if we have any more pb on this, redo all : load payment from session and copy data in from dto.
session.merge(reglement);
}
Pleaase help me to understand what is wrong in xml, because it says error while building session factory itself.
XML :
<!-- Many to Many starts -->
<class name="Bishop" table="BISHOP">
<id name="id" column="BISHOP_ID">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="churches" table="BISHOP_CHURCH" inverse="true" cascade="all">
<key column="CHURCH_ID" />
<many-to-many column="BISHOP_ID" />
</set>
</class>
<class name="Church" table="CHURCH">
<id name="id" column="CHURCH_ID">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="bishops" table="BISHOP_CHURCH" inverse="true">
<key column="CHURCH_ID" />
<many-to-many column="BISHOP_ID" />
</set>
</class>
<!-- Many to Many ends -->
Main Class :
SessionFactory sessionFactory = new Configuration()
.configure("hibernate.cfg.xml")
.buildSessionFactory(); // this is 23 line error comes.
Bishop b1 = new Bishop();
b1.setName("bishop1");
Bishop b2 = new Bishop();
b2.setName("bishop2");
Set<Bishop> bishops = new HashSet<>();
bishops.add(b1);
bishops.add(b2);
Church c1 = new Church();
c1.setName("church1");
Church c2 = new Church();
c2.setName("church2");
c1.setBishops(bishops);
c2.setBishops(bishops);
Set<Church> churches = new HashSet<>();
churches.add(c1);
churches.add(c2);
b1.setChurches(churches);
b2.setChurches(churches);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(b1);
session.save(b2);
session.getTransaction().commit();
session.close();
POJOs :
public class Bishop {
private int id;
private String name;
private Set<Church> churches;
//getters & setters
}
public class Church {
private int id;
private String name;
private Set<Bishop> bishops;
//getters & setters
}
Exception :
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.mapping.Table$ForeignKeyKey.equals(Table.java:95)
at java.util.HashMap.getEntry(HashMap.java:448)
at java.util.LinkedHashMap.get(LinkedHashMap.java:301)
at org.hibernate.mapping.Table.createForeignKey(Table.java:658)
at org.hibernate.mapping.Table.createForeignKey(Table.java:651)
at org.hibernate.mapping.SimpleValue.createForeignKeyOfEntity(SimpleValue.java:147)
at org.hibernate.mapping.ManyToOne.createForeignKey(ManyToOne.java:61)
at org.hibernate.mapping.Collection.createForeignKeys(Collection.java:419)
at org.hibernate.mapping.Collection.createAllKeys(Collection.java:428)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:71)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1695)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at sample.pack.TestMany2ManyXML.main(TestMany2ManyXML.java:23)
Can you please try with the below xml.
<!-- Many to Many starts -->
<class name="Bishop" table="BISHOP">
<id name="id" column="BISHOP_ID">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="churches" table="BISHOP_CHURCH" inverse="false" lazy="true" fetch="select" cascade="all">
<key>
<column name="CHURCH_ID" not-null="true" />
</key>
<many-to-many entity-name="com.*.*.Church">
<column name="BISHOP_ID" not-null="true" />
</many-to-many>
</set>
</class>
<class name="Church" table="CHURCH">
<id name="id" column="CHURCH_ID">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="bishops" table="BISHOP_CHURCH" inverse="true" lazy="true" fetch="select">
<key>
<column name="CHURCH_ID" not-null="true" />
</key>
<many-to-many entity-name="com.*.*.Bishop">
<column name="BISHOP_ID" not-null="true" />
</many-to-many>
</set>
</class>
<!-- Many to Many ends -->
i have a web project where is use Spring 3.1.1.RELEASE, Hibernate 4.2.0.Final , mysql version '5.5.19-enterprise-commercial-advanced-log' and junit 4.7
I'm doing my unit testing, i test my CRUD operations.
I made several test and almost all are fine, the problem is in group-event relationship, in update test, i want create a group and many events, set the list (HashSet in the strict sense) a send the group to the service, likewise the update method. Create works fine, but not update :(
Classes
public class Group implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer groupID;
private User user;
private Integer userID;
private User userManegement;
private Integer userManagementID;
private Date deteIni;
private Set<Event> events;
private Set<StatusGroup> status;
//get
//set
....
public class Event implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer eventID;
private Integer groupID;
private Date dateIni;
private Date dateTwo;
private String help;
private String commet;
private Group group;
//get
//set
......
Mapping
<?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 18/03/2014 09:58:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.my.dev.mysql.Group" table="Group">
<id name="groupID" type="java.lang.Integer">
<column name="id_group" />
<generator class="identity" />
</id>
<many-to-one name="user" column="user_id" foreign-key="id_user" class="com.my.dev.mysql.User"
fetch="join" update="false" insert="false">
</many-to-one>
<property name="userID" type="java.lang.Integer">
<column name="user_id" />
</property>
<many-to-one name="userManegement" column="user_management_id" foreign-key="id_user" class="com.my.dev.mysql.User"
fetch="join" update="false" insert="false">
</many-to-one>
<property name="userManagementID" type="java.lang.Integer">
<column name="user_management_id" />
</property>
<property name="deteIni" type="java.util.Date">
<column name="dete_ini" sql-type="DATE" not-null="true" />
</property>
<set name="events">
<key>
<column name="group_id" />
</key>
<one-to-many class="com.my.dev.mysql.Event" />
</set>
<set name="status">
<key>
<column name="group_id" />
</key>
<one-to-many class="com.my.dev.mysql.StatusGroup" />
</set>
</class>
</hibernate-mapping>
<?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 18/03/2014 09:58:25 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.my.dev.mysql.Event" table="EVENT">
<id name="eventID" type="java.lang.Integer">
<column name="id_event" />
<generator class="identity" />
</id>
<property name="groupID" type="java.lang.Integer" not-null="true">
<column name="group_id" />
</property>
<property name="dateIni" type="java.util.Date" not-null="true">
<column name="date_ini" sql-type="TIMESTAMP" not-null="true" />
</property>
<property name="dateTwo" type="java.util.Date" not-null="true">
<column name="date_two" sql-type="TIMESTAMP" not-null="true" />
</property>
<property name="help" type="java.lang.String">
<column name="help" not-null="true" />
</property>
<property name="commet" type="java.lang.String">
<column name="commet" not-null="true" />
</property>
<many-to-one name="group" column="group_id" foreign-key="id_group" class="com.my.dev.mysql.Group"
fetch="join" update="false" insert="false">
</many-to-one>
</class>
</hibernate-mapping>
My Unit Test
#RunWith(SpringJUnit4ClassRunner.class)
#TestExecutionListeners({ TransactionalTestExecutionListener.class, DependencyInjectionTestExecutionListener.class })
#ContextConfiguration(locations = { "/testEnvironment.xml" })
public class GroupServiceImplTest {
#Autowired
private GroupService groupService;
#Test //THIS TEST WORKS FINE
public void create() {
FormBeanGroup form = new FormBeanGroup();
form.setDate("24/03/2014");
List<Event> events = new ArrayList<Event>();
for (int i = 0; i < 8; i++) {
Event event = new Event();
event.setHelp("help -" + Randomizer.getNumSRandom());
event.setDateTwo(Calendar.getInstance().getTime());
Calendar now = Calendar.getInstance();
now.set(Calendar.DAY_OF_YEAR, now.get(Calendar.DAY_OF_YEAR) - i);
event.setDate(now.getTime());
event.setCommet("ubicacion ");
events.add(event);
}
form.setEvents(events);
try {
groupService.save(form);
} catch (GenericException e) {
e.printStackTrace();
}
}
#Test //THIS TEST WORKS FINE
public void get(){
Group group = groupService.getById(40);
System.out.println(group);
assertNotNull(group);
assertEquals(group.getStatus().get() , TypeGroup.ALFA);
}
#Test //THIS TEST WORKS FINE
public void delete(){
groupService.borrarEvents(41);
}
#Test // f*****in TEST
public void update() {
FormaCapturaGroup form = new FormaCapturaGroup();
form.setDate("24/03/2014");
form.setId(40);
List<Event> events = new ArrayList<Event>();
// for (int i = 0, k = 250; i < 8; i++, k++) { //fill events, but i comment, trying to find the error
form.setEvents(events);
try {
groupService.update(form);
} catch (GenericException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The service
#Transactional
public void update(FormBeanGroup form) throws GenericException {
Group group = groupDao.getById(form.getId());
if (group != null) {
//more code comment beacuse i trying to find the error
group.setEvents(new HashSet<Event>(form.getEvents())); //fix chrome grammar spelling
groupDao.update(group);
System.out.println("post");
}
}
The dao
public Group update(com.segurosargos.siga.modelo.mysql.Group group)
throws GenericException {
System.out.println("DAO{Update} ");
System.out.println(group);
//really 100 lines commet
//Believe me seriously.
//this is all code in update method
return null;
}
When i run the test update throws this error:
org.springframework.dao.DataIntegrityViolationException: could not perform addBatch; SQL [update EVENT set group_id=null where group_id=?]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not perform addBatch
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:159)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:606)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:488)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy18.update(Unknown Source)
at com.my.dev.service.impl.GroupServiceImplTest.update(AgendaServiceImplTest.java:129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.exception.ConstraintViolationException: could not perform addBatch
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:128)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:114)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(BatchingBatch.java:101)
at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(AbstractBatchImpl.java:149)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(JdbcCoordinatorImpl.java:198)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:357)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:277)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:328)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1233)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:403)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:480)
... 36 more
Caused by: java.sql.BatchUpdateException: Column 'group_id' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:110)
... 48 more
And log
post
Hibernate:
update
EVENT
set
group_id=null
where
group_id=?
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1048, SQLState: 23000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Column 'group_id' cannot be null
Yes group_id is NOT NULL but Why this update occurs?.
While testing my code comment much, provided each time this exception was produced, which he attributed to him something I had done. but not.
In fact change the column to accept null, and my test worked well, both within my unit test and database were restated things right.
I keep wondering why this happens, this magical update I never do, is what I'm doing wrong, please I need your help.
The problem is that when this instruction is executed:
group.setEventos(new HashSet<Evento>(form.getEventos()));
there are new events linked to the group. This means that the events previously linked to the group are no longer linked it to it anymore.
In order to break this link in the database Hibernate needs to update the foreign key EVENT.group_id to null, and that is the reason why the update is made.
The events previously linked to the group will go on existing as separate entities in the database, without being attached to any group.
This is because Event is an #Entity and not an #Embeddable, so it can exist without being related to a Group. But setting the foreign key column to not-nullable sort of goes against this and causes Hibernate to try to update a non nullable column.
The mapping then needs to be updated either to make Event an #Embeddable that cannot exist without a group, or declare the foreign key as nullable.
I am using hibernate in my java program and I got some troubles using it ..
Here is my xml:
<hibernate-mapping>
<class name="revEngMapping.TestNetwork" table="testNetwork">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="networkElementId" type="string">
<column name="networkElement_id" length="45" />
</property>
<property name="date" type="string">
<column name="Date" length="45" />
</property>
<property name="oid" type="string">
<column name="Oid" length="150" />
</property>
<property name="value" type="string">
<column name="Value" length="200" />
</property>
</class>
here is my java class:
public class TestNetwork implements java.io.Serializable {
private Integer id;
private String networkElementId;
private String date;
private String oid;
private String value;
public TestNetwork() {
}
public TestNetwork(String networkElementId, String date, String oid,
String value) {
this.networkElementId = networkElementId;
this.date = date;
this.oid = oid;
this.value = value;
}
Then its just getters and setters, and in my main, I just want to display it:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Criteria crit = session.createCriteria(TestNetwork.class);
List resultList=crit.list();
for(int i=0;i<resultList.size();i++)
System.out.println(((TestNetwork)resultList.get(i)).getId()+" "+((TestNetwork)resultList.get(i)).getDate());
session.getTransaction().commit();
In my console it says that I have an SQL error ..
10:20:54,626 WARN JDBCExceptionReporter:233 - SQL Error: 1064, SQLState: 42000
10:20:54,628 ERROR JDBCExceptionReporter:234 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.testNetwork this_' at line 1
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2536)
Hope s.one can help. thanks
mysql requires you to use backticks `` when accessing table names & columns, please back ticks while defining
eg..
<property name="someProperty" column="`dbColumnName`"/>
this should solve your problem..
Anantha Sharma