-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: merge() does not respect @UniqueConstraint ?
PostPosted: Sat Aug 19, 2006 8:04 am 
Newbie

Joined: Fri Aug 18, 2006 11:54 am
Posts: 11
Hibernate version: 3.2.0.cr2
Name and version of the database you are using: MySQL 4.1

I have EJB3 Entity with one @Id column and two other columns which are combined to a unique key.
I need to fill DB with a list of this entities from file. Unfortunately in this file are duplicated entities. (This unique key, not id is duplicated.)

I've tried to simply create entity and persist() it, but the "Duplicate entry" exception happens. Then I've changed persist() to merge(), but this did not help. (I've checked SQL logs, and found hibernate did not check if entity exist before inserting. Anyway, i don't need this check.)

I can use native SQL REPLACE statement, but... this is just not an elegant aproach...
Is there something in persistence api to solve my task?

Source code:
Code:
@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"razdel", "kod"}))
public class Team implements Serializable {
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
   
    private int razdel;
    private int kod;
    @OneToMany(mappedBy="team", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @MapKey(name="lang")
    private Map<String, TeamName> names;

    //constructor, getters, setters, hashCode() and  equals() methods are ommited
}

//insertion code:
    @PersistenceContext
    private EntityManager em;
    //...
    public void loadTeamFile() {
        Iterator<TeamRecord> it; //this is Iterator for entries in the file
        //...
        while(it.hasNext()){
            TeamRecord r = it.next();
            Team t = new Team(r.getKodRazdel(), r.getKod());
            Map<String, TeamName> m = new HashMap<String, TeamName>();
            m.put("ru", new TeamName(t, "ru", r.getNaim()[0]));
            m.put("en", new TeamName(t, "en", r.getNaim()[1]));
            t.setNames(m);
            em.merge(t);
        }
        em.flush();
    }


Full stack trace of any exception that occurs:
Code:
javax.ejb.EJBException: javax.persistence.EntityExistsException: org.hibernate.exception.ConstraintViolationException: could not insert: [com.fonbet.lineconfig.Team]
   at org.jboss.ejb3.tx.Ejb3TxPolicy.handleExceptionInOurTx(Ejb3TxPolicy.java:69)
   at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:83)
   at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:197)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.aspects.tx.TxPropagationInterceptor.invoke(TxPropagationInterceptor.java:76)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.stateless.StatelessInstanceInterceptor.invoke(StatelessInstanceInterceptor.java:62)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.aspects.security.AuthenticationInterceptor.invoke(AuthenticationInterceptor.java:78)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.ENCPropagationInterceptor.invoke(ENCPropagationInterceptor.java:47)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.asynchronous.AsynchronousInterceptor.invoke(AsynchronousInterceptor.java:106)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.stateless.StatelessContainer.localInvoke(StatelessContainer.java:181)
   at org.jboss.ejb3.stateless.StatelessLocalProxy.invoke(StatelessLocalProxy.java:79)
   at $Proxy227.loadTeamFile(Unknown Source)
   at org.apache.jsp.configManager_jsp._jspService(configManager_jsp.java:88)
   at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
   at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
   at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
   at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
   at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
   at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
   at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
   at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
   at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
   at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
   at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
   at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
   at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
   at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
   at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
   at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
   at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
   at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
   at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
   at java.lang.Thread.run(Thread.java:595)
Caused by: javax.persistence.EntityExistsException: org.hibernate.exception.ConstraintViolationException: could not insert: [com.fonbet.lineconfig.Team]
   at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:555)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:210)
   at org.jboss.ejb3.entity.TransactionScopedEntityManager.merge(TransactionScopedEntityManager.java:181)
   at com.fonbet.lineconfig.ConfigManagerBean.loadTeamFile(ConfigManagerBean.java:54)
   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:585)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:112)
   at org.jboss.ejb3.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:166)
   at org.jboss.ejb3.interceptor.EJB3InterceptorsInterceptor.invoke(EJB3InterceptorsInterceptor.java:63)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.entity.TransactionScopedEntityManagerInterceptor.invoke(TransactionScopedEntityManagerInterceptor.java:54)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.ejb3.AllowedOperationsInterceptor.invoke(AllowedOperationsInterceptor.java:47)
   at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
   at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:79)
   ... 40 more
Caused by: org.hibernate.exception.ConstraintViolationException: could not insert: [com.fonbet.lineconfig.Team]
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
   at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:40)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2044)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2481)
   at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:47)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
   at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
   at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
   at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
   at org.hibernate.event.def.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:165)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:102)
   at org.hibernate.event.def.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:51)
   at org.hibernate.impl.SessionImpl.fireMerge(SessionImpl.java:679)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:663)
   at org.hibernate.impl.SessionImpl.merge(SessionImpl.java:667)
   at org.hibernate.ejb.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:201)
   ... 55 more
Caused by: java.sql.SQLException: Duplicate entry '44-186' for key 2
   at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2928)
   at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1571)
   at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1124)
   at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:676)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1166)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1082)
   at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1067)
   at org.jboss.resource.adapter.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:251)
   at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73)
   at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33)
   ... 69 more


Top
 Profile  
 
 Post subject:
PostPosted: Sun Aug 20, 2006 1:19 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
@UniqueConstraint is for DDL generation only. The runtime behavior is not affected. You are responsible for the unicity test if you don't want to rely on the DB constraint

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Sun Aug 20, 2006 1:44 pm 
Newbie

Joined: Fri Aug 18, 2006 11:54 am
Posts: 11
Well, I would like to rely on hibernate an DB for unicity, i just don't know how to do this.
I need to ensure there is only one record with certain "kod" and "razdel" fields, and the only thing I found is @UniqueConstraint annotation.

How can i ask hibernate to check this unicity?


Top
 Profile  
 
 Post subject:
PostPosted: Sun Aug 20, 2006 1:50 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
do a query :-)

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Sun Aug 20, 2006 2:11 pm 
Newbie

Joined: Fri Aug 18, 2006 11:54 am
Posts: 11
Then I will have 10 000 insert and 10 000 select queries... And it will be 2 times longer... :(


Top
 Profile  
 
 Post subject: Re: merge() does not respect @UniqueConstraint ?
PostPosted: Mon Oct 26, 2009 7:56 pm 
Newbie

Joined: Sun Oct 11, 2009 7:17 pm
Posts: 8
I'm working on a problem like this. Did you find a good way to do it?

I'm looking into something like this

Code:
Session s = HibernateUtil.getCurrentSession();
      
for (String sql : sqlList) {

    Query query = s.createSQLQuery(sql);
    query.executeUpdate();
    s.getTransaction().commit();
}

_________________
Kremsoft
Software Development Outsourcing http://www.kremsoft.com


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.