-->
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.  [ 2 posts ] 
Author Message
 Post subject: MS-SQL 05 Auto-Increment Identity in composite key issue
PostPosted: Wed May 26, 2010 10:12 am 
Newbie

Joined: Wed May 26, 2010 9:52 am
Posts: 1
I've got a table with a composite key within which is an auto-increment value. I am unable to get hibernate to insert new records into the table. I will refrain from cutting out any code so you get as complete a picture as possible.

Let me explain what's going on to save time on reading the code. The table has 5 fields in the key: sourceApplication, optionId, groupId, memberId, and seqNo. SeqNo is the auto-increment value. I am able to update values, but cannot insert new ones. The following is the entity code, DAO code, SQL table definition, and stacktrace.

Things I've tried:
    Adding generator="native" in GeneratedValue
    Adding generator="increment" in GeneratedValue
    Adding generator="identity" in GeneratedValue
    strategy=GenerationType.AUTO
    Moving annotations around from the field declaration to the getter

Entity Code
Code:
package com.bcbst.bamp.ws.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.bcbst.bamp.ws.common.Globals;

/**
* BampiEntity implementation class for BampiEntity: MemberSelectedOption
*
*/
@Entity
@Table(schema="dbo", name="MemberSelectedOptions")
public class MemberSelectedOption extends BampiEntity implements Serializable {

   @Embeddable
   public static class MSOPK implements Serializable {
      private static final long serialVersionUID = 1L;
      
      @Column(name="SourceApplication", updatable=false)
      String sourceApplication;
      
      @Column(name="GroupId")
      String groupId;
      
      @Column(name="MemberId")
      String memberId;
      
      @Column(name="OptionId", updatable=false)
      int optionId;
         
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      @Column(name="SeqNo")
      BigDecimal seqNo;
      
      public BigDecimal getSeqNo() {
         return seqNo;
      }
      
      public String getSourceApplication() {
         return sourceApplication == null?null:sourceApplication.trim();
      }

      public void setSourceApplication(String sourceApplication) {
         this.sourceApplication = sourceApplication == null?null:sourceApplication.trim();
      }

      public String getGroupId() {
         return groupId == null?null:groupId.trim();
      }

      public void setGroupId(String groupId) {
         this.groupId = groupId == null?null:groupId.trim();
      }

      public String getMemberId() {
         return memberId == null?null:memberId.trim();
      }

      public void setMemberId(String memberId) {
         this.memberId = memberId == null?null:memberId.trim();
      }

      public int getOptionId() {
         return optionId;
      }

      public void setOptionId(int optionId) {
         this.optionId = optionId;
      }

      public static long getSerialVersionUID() {
         return serialVersionUID;
      }
      public boolean equals(Object obj){
         MSOPK rhs = (MSOPK)obj;
         return  this.groupId.equals(rhs.groupId) &&
               this.memberId.equals(rhs.memberId) &&
               this.optionId == rhs.optionId &&
               this.sourceApplication.equals(rhs.sourceApplication);
      }
      
      public int hashCode(){
         return new StringBuilder().append(groupId)
                           .append(memberId)
                           .append(optionId)
                           .append(sourceApplication)
                           .hashCode();
      }
      
   }
   
   private static final long serialVersionUID = 1L;
   
   @EmbeddedId
   MSOPK pk = new MSOPK();
   
   @Column(name="OptionStatusCd")
   String optionStatusCd;
   
   @Column(name="EffectiveDate")
   Date effectiveDate;
   
   @Column(name="TermDate")
   Date termDate;
   
   @Column(name="SelectionStatusDate")
   Date selectionStatusDate;   
   
   @Column(name="SysLstUpdtUserId")
   String sysLstUpdtUserId = Globals.WS_USER_ID;
   
   @Column(name="SysLstTrxDtm")
   Date sysLstTrxDtm = new Date();
   
   @OneToMany(mappedBy="option")
   List<MemberSelectedVariable> variables = new ArrayList<MemberSelectedVariable>();

   public List<MemberSelectedVariable> getVariables() {
      return variables;
   }

   public void setVariables(List<MemberSelectedVariable> variables) {
      this.variables = variables;
   }
   
   public void addVariable(MemberSelectedVariable var){
      if(variables == null){
         variables = new ArrayList<MemberSelectedVariable>();
      }
      variables.add(var);
   }
   
   public void removeVariable(MemberSelectedVariable var){
      if(variables == null){
         variables = new ArrayList<MemberSelectedVariable>();
      }
      if(variables.contains(var))
         variables.remove(var);
   }

   public MemberSelectedOption() {
      super();
   }
   
   public String getSourceApplication() {
      return pk.getSourceApplication();
   }

   public void setSourceApplication(String sourceApplication) {
      this.pk.setSourceApplication(sourceApplication);
   }

   public String getGroupId() {
      return pk.getGroupId();
   }

   public void setGroupId(String groupId) {
      this.pk.setGroupId(groupId);
   }

   public String getMemberId() {
      return pk.getMemberId();
   }

   public void setMemberId(String memberId) {
      this.pk.setMemberId(memberId);
   }

   public int getOptionId() {
      return pk.getOptionId();
   }

   public void setOptionId(int optionId) {
      this.pk.setOptionId(optionId);
   }
   
   public BigDecimal getSeqNo() {
      return pk.seqNo;
   }

   public String getOptionStatusCd() {
      return optionStatusCd == null?null:optionStatusCd.trim();
   }

   public void setOptionStatusCd(String optionStatusCd) {
      this.optionStatusCd = optionStatusCd == null?null:optionStatusCd.trim();
   }

   public Date getSelectionStatusDate() {
      return selectionStatusDate;
   }

   public void setSelectionStatusDate(Date selectionStatusDate) {
      this.selectionStatusDate = selectionStatusDate;
   }

   public String getSysLstUpdtUserId() {
      return sysLstUpdtUserId == null?null:sysLstUpdtUserId.trim();
   }

   public void setSysLstUpdtUserId(String sysLstUpdtUserId) {
      this.sysLstUpdtUserId = sysLstUpdtUserId == null?null:sysLstUpdtUserId.trim();
   }

   public Date getSysLstTrxDtm() {
      return sysLstTrxDtm;
   }

   public void setSysLstTrxDtm(Date sysLstTrxDtm) {
      this.sysLstTrxDtm = sysLstTrxDtm;
   }

   public static long getSerialVersionUID() {
      return serialVersionUID;
   }

   public Date getEffectiveDate() {
      return effectiveDate;
   }

   public void setEffectiveDate(Date effectiveDate) {
      this.effectiveDate = effectiveDate;
   }

   public Date getTermDate() {
      return termDate;
   }

   public void setTermDate(Date termDate) {
      this.termDate = termDate;
   }
   
   
   
}


DAO Code
Code:
public void saveMemberSelectedOption(List<MemberSelectedOption> list) {
      Session session = null;
      try {
         session = getHibernateTemplate().getSessionFactory().openSession();
         session.beginTransaction();
         
         MemberSelectedOption obj = new MemberSelectedOption();
         obj.setSourceApplication("bampi");
         obj.setOptionId(260);
         obj.setMemberId("1234");
         obj.setGroupId("1234");
         
         session.save(obj);
         session.getTransaction().commit();
      } catch (HibernateException e) {
         e.printStackTrace();
         throw e;
      } finally {
         if(session != null)
            session.close();
      }
   }



Table Definition
Code:
USE [BAMPI_TP_dev]
GO
/****** Object:  Table [dbo].[MemberSelectedOptions]    Script Date: 05/26/2010 10:05:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MemberSelectedOptions](
   [SourceApplication] [char](8) NOT NULL,
   [GroupId] [char](8) NOT NULL,
   [MemberId] [char](12) NOT NULL,
   [OptionId] [int] NOT NULL,
   [SeqNo] [int] IDENTITY(1,1) NOT NULL,
   [OptionStatusCd] [char](1) NULL,
   [EffectiveDate] [datetime] NULL,
   [TermDate] [datetime] NULL,
   [SelectionStatusDate] [datetime] NULL,
   [SysLstUpdtUserId] [char](10) NOT NULL,
   [SysLstTrxDtm] [datetime] NOT NULL CONSTRAINT [DF_MemberSelectedOptions_SysLstTrxDtm]  DEFAULT (getdate())
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF


StackTrace You can clearly see where the SQL is trying to insert a value for SeqNo.
Code:
[5/26/10 10:07:19:946 EDT] 0000003d SystemOut     O Hibernate: insert into dbo.MemberSelectedOptions (OptionStatusCd, EffectiveDate, TermDate, SelectionStatusDate, SysLstUpdtUserId, SysLstTrxDtm, SourceApplication, GroupId, MemberId, OptionId, SeqNo) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
[5/26/10 10:07:19:961 EDT] 0000003d JDBCException W org.slf4j.impl.JCLLoggerAdapter warn SQL Error: 544, SQLState: S0001
[5/26/10 10:07:19:961 EDT] 0000003d JDBCException E org.slf4j.impl.JCLLoggerAdapter error Cannot insert explicit value for identity column in table 'MemberSelectedOptions' when IDENTITY_INSERT is set to OFF.
[5/26/10 10:07:19:961 EDT] 0000003d AbstractFlush E org.slf4j.impl.JCLLoggerAdapter error Could not synchronize database state with session
                                 org.hibernate.exception.SQLGrammarException: could not insert: [com.bcbst.bamp.ws.model.MemberSelectedOption]
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2285)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678)
   at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
   at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
   at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
   at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
   at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
   at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
   at com.bcbst.bamp.ws.dao.MemberSelectedOptionDAOImpl.saveMemberSelectedOption(MemberSelectedOptionDAOImpl.java:135)
   at com.bcbst.bamp.ws.common.AlertReminder.saveMemberSelectedOptions(AlertReminder.java:92)
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
   at java.lang.reflect.Method.invoke(Method.java:599)
   at org.apache.axis2.jaxws.server.dispatcher.JavaDispatcher.invokeTargetOperation(JavaDispatcher.java:81)
   at org.apache.axis2.jaxws.server.dispatcher.JavaBeanDispatcher.invoke(JavaBeanDispatcher.java:98)
   at org.apache.axis2.jaxws.server.EndpointController.invoke(EndpointController.java:109)
   at org.apache.axis2.jaxws.server.JAXWSMessageReceiver.receive(JAXWSMessageReceiver.java:159)
   at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:188)
   at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275)
   at com.ibm.ws.websvcs.transport.http.WASAxis2Servlet.doPost(WASAxis2Servlet.java:1389)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:738)
   at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
   at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1586)
   at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:868)
   at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:474)
   at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:175)
   at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3742)
   at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:276)
   at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:932)
   at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583)
   at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:175)
   at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
   at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
   at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272)
   at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
   at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
   at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
   at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
   at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
   at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
   at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
   at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
   at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
   at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert explicit value for identity column in table 'MemberSelectedOptions' when IDENTITY_INSERT is set to OFF.
   at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(Unknown Source)
   at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source)
   at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(Unknown Source)
   at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.executeUpdate(WSJdbcPreparedStatement.java:797)
   at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46)
   at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2265)
   ... 47 more


Top
 Profile  
 
 Post subject: Re: MS-SQL 05 Auto-Increment Identity in composite key issue
PostPosted: Wed May 26, 2010 1:09 pm 
Expert
Expert

Joined: Wed Mar 03, 2004 6:35 am
Posts: 1240
Location: Lund, Sweden
According to the documentation at http://docs.jboss.org/hibernate/stable/ ... ompositeid Hibernate doesn't support composite keys with generators. Here is the relevant part:

Quote:
You cannot use an IdentifierGenerator to generate composite keys. Instead the application must assign its own identifiers.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 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.