как вставить несколько записей одновременно в спящем режиме - PullRequest
0 голосов
/ 16 мая 2018

Я хочу вставить несколько записей одновременно в цикле, используя Hibernate

я пробовал с кодом ниже

сервисный метод, который вызывает метод вставки

@Override
    @Transactional
    public boolean addTermdates(FeeTermDates feetermdates) {
        // TODO Auto-generated method stub
        return theMasterDao.addTermdates(feetermdates);
    }

DAO

@Override
    public boolean addTermdates(FeeTermDates feetermdates) {

        int termid=feetermdates.getFeeTerms().getTermId();
        FeeTerms feeTerms=new FeeTerms();
        feeTerms.setTermId(termid);
         boolean success = false;
         try {
                currentSession=sessionFactory.getCurrentSession();

                String stringDate=feetermdates.getDate();
                FeeTermDates feeDate=null;
                String val[]=stringDate.split(",");
                int i=0;
                for(String date:val)
                {
                    i++;

                    feeDate=new FeeTermDates();
                    feeDate.setFeeTerms(feeTerms); 
                    feeDate.setDate(date);
                    currentSession.save(feeDate);    

                }  


                success=true;  

         }  
         catch (Exception e) {  
            e.printStackTrace();
        }
        return success;
    }    

но он вставляет только одну запись после создания исключения . Пожалуйста, посмотрите на исключение

org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.rasvek.cg.entity.FeeTermDates#0]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:169)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:691)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:683)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:678)
    at com.rasvek.cms.dao.MasterDaoImpl.addTermdates(MasterDaoImpl.java:380)
    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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy1553.addTermdates(Unknown Source)
    at com.rasvek.cms.service.MasterSeviceImpl.addTermdates(MasterSeviceImpl.java:150)
    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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy1554.addTermdates(Unknown Source)
    at com.rasvek.cms.controller.MasterController.addTermdates(MasterController.java:600)
    at com.rasvek.cms.controller.MasterController$$FastClassBySpringCGLIB$$c2eff8c2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.rasvek.cms.controller.MasterController$$EnhancerBySpringCGLIB$$8a38b6e5.addTermdates(<generated>)
    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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Hibernate: insert into campus_guru_01.fee_term_dates (date, term_id, tdm_id) values (?, ?, ?)

> можно ли это сделать в спящем режиме?

если да, пожалуйста, помогите мне.

редактировать

package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * FeeTerms generated by hbm2java
 */
@Entity
@Table(name = "fee_terms", catalog = "campus_guru_01")
public class FeeTerms implements java.io.Serializable {

    private Integer termId;
    private String termName;
    private String termCount;
    private Set<FeeTermDates> feeTermDateses = new HashSet<FeeTermDates>(0);
    private Set<AssocFeeTerms> assocFeeTermses = new HashSet<AssocFeeTerms>(0);

    public FeeTerms() {
    }

    public FeeTerms(String termName, String termCount, Set<FeeTermDates> feeTermDateses,
            Set<AssocFeeTerms> assocFeeTermses) {
        this.termName = termName;
        this.termCount = termCount;
        this.feeTermDateses = feeTermDateses;
        this.assocFeeTermses = assocFeeTermses;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "term_id", unique = true, nullable = false)
    public Integer getTermId() {
        return this.termId;
    }

    public void setTermId(Integer termId) {
        this.termId = termId;
    }

    @Column(name = "term_name")
    public String getTermName() {
        return this.termName;
    }

    public void setTermName(String termName) {
        this.termName = termName;
    }

    @Column(name = "term_count", length = 45)
    public String getTermCount() {
        return this.termCount;
    }

    public void setTermCount(String termCount) {
        this.termCount = termCount;
    }  

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
    public Set<FeeTermDates> getFeeTermDateses() {
        return this.feeTermDateses;
    }  

    public void setFeeTermDateses(Set<FeeTermDates> feeTermDateses) {
        this.feeTermDateses = feeTermDateses;
    }

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "feeTerms")
    public Set<AssocFeeTerms> getAssocFeeTermses() {
        return this.assocFeeTermses;
    }

    public void setAssocFeeTermses(Set<AssocFeeTerms> assocFeeTermses) {
        this.assocFeeTermses = assocFeeTermses;
    }

}

FeeTermDates.java

package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * FeeTermDates generated by hbm2java
 */
@Entity
@Table(name = "fee_term_dates", catalog = "campus_guru_01")
public class FeeTermDates implements java.io.Serializable {

    private int tdmId;
    private FeeTerms feeTerms;
    private String date;

    public FeeTermDates() {
    }

    public FeeTermDates(int tdmId, FeeTerms feeTerms) {
        this.tdmId = tdmId;
        this.feeTerms = feeTerms;
    }

    public FeeTermDates(int tdmId, FeeTerms feeTerms, String date) {
        this.tdmId = tdmId;
        this.feeTerms = feeTerms;
        this.date = date;
    }

    @Id

    @Column(name = "tdm_id", unique = true, nullable = false)
    public int getTdmId() {
        return this.tdmId;
    }

    public void setTdmId(int tdmId) {
        this.tdmId = tdmId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "term_id", nullable = false)
    public FeeTerms getFeeTerms() {
        return this.feeTerms;  
    }  

    public void setFeeTerms(FeeTerms feeTerms) {
        this.feeTerms = feeTerms;
    }

    @Column(name = "date")
    public String getDate() {
        return this.date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}

1 Ответ

0 голосов
/ 16 мая 2018

Да, это возможно.

Но ваша проблема на основе стековой трассировки, кажется, указывает на то, что когда вы вставляете вторую сущность FeeTermDates, ей назначается тот же первичный ключ 0.

Если вы назначаете первичный ключ вашей сущности для назначения вручную, как показано ниже, то, что вы правильно назначаете значение в цикле.

@Id
private Integer id;

Другой вариант - позволить базе данных назначить ее для вас, позволив базе данных сгенерировать для вас значение, чтобы вы могли сосредоточиться только на построении сущности с бизнес-данными:

@Id
@GeneratedValue
private Integer id;

Полагаю, вы используете опцию (1), но не назначаете значение. Я предлагаю использовать вариант (2) для вашего случая использования, если это возможно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...