Search code examples
javaspring-boothibernateannotationsmapping

Spring Boot CRUD operations with hibernate


I have a problem on deleting the record from MySQL DB. According to logs there is a problem at line:45 in my DeleteProductOfferDAOImpl.deleteProductOffer Method

Here is the logs:
    com.sixdee.product.exception.ResourceNotFoundException: Resource is not available 136
        at com.sixdee.product.dao.DeleteProductOfferDAOImpl.deleteProductOffer(DeleteProductOfferDAOImpl.java:45)
        at com.sixdee.product.dao.DeleteProductOfferDAOImpl$$FastClassBySpringCGLIB$$d1ef7c0.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
        at com.sixdee.product.dao.DeleteProductOfferDAOImpl$$EnhancerBySpringCGLIB$$4a15e7e.deleteProductOffer(<generated>)
        at com.sixdee.product.services.DeleteProductOfferServiceImpl.deleteProductOffer(DeleteProductOfferServiceImpl.java:20)
        at com.sixdee.product.services.DeleteProductOfferServiceImpl$$FastClassBySpringCGLIB$$1ded266b.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:771)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
        at com.sixdee.product.services.DeleteProductOfferServiceImpl$$EnhancerBySpringCGLIB$$333ced5f.deleteProductOffer(<generated>)
        at com.sixdee.product.controller.DeleteProductOfferController.deleteProductOffer(DeleteProductOfferController.java:31)
        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:190)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:666)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        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)

DeleteProductOfferDAOImpl:

@Repository class

    private EntityManager entityManager;
    @Autowired
    public DeleteProductOfferDAOImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    @Autowired
    private ProductOffer productOffer;
    @Override
    @Transactional
    public void deleteProductOffer(String operation, String offerCode, String version) {
        Session session = null;
        try {
            // get the current hibernate session
            session = entityManager.unwrap(Session.class);
            System.out.println("delete " + (OperationEnum.fromValue(operation) == OperationEnum.PUBLISH) );
            if (OperationEnum.fromValue(operation) == OperationEnum.PUBLISH) {
                if (offerCode == productOffer.getOfferCode() && version == productOffer.getVersion()) {
                    String query = "update product_offer_table set status='Interim-Active' where offerCode ='"+offerCode+"'& version ='"+version+"'";
                    session.createSQLQuery(query).executeUpdate();
                    //ProductOffer productOffer = (ProductOffer) session.load(ProductOffer.class, offerCode);
                } else {
                    throw new ResourceNotFoundException("Resource is not available " + offerCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ProductOffer:

@Entity
@Table(name = "product_offer_table")
@Component
public class ProductOffer implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "offer_code", nullable = false)
    // @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String offerCode = null;

    @NotNull
    // @Size(max = 100)
    @Column(unique = true)
    private String version = null;

    @Column(name = "offerCode_version", length = 50)
    private String offerCode_version = null;

    @Column(nullable = false)
    private String offerName = null;

    @Column
    private String description = null;

    @Column
    private Boolean isBundle = false;

    @Column
    private Boolean isSellable = true;

    @Column
    private Boolean isLoyaltyRedeemable = false;

    @Column
    private Boolean isRecommendable = false;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "lcsId")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private LifeCycleStatus lifecycleStatus = null;

    @Column
    private String status = null;

    @Column
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date startDate = null;

    @Column
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date endDate = null;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "pogId")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private ProductOfferGroupMaster productOfferGroup = null;

    @OneToMany(targetEntity = ProductOfferNomenclature.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "pnmKey")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private List<ProductOfferNomenclature> nomenclatures = null;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "popKey")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private ProductOfferPrice productOfferPrice = null;

    @OneToMany(targetEntity = ProductSpecCharacteristics.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "pscKey")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    private List<ProductSpecCharacteristics> productSpecCharacteristics = new ArrayList<ProductSpecCharacteristics>();

    // @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_date", updatable = false)
    @CreatedDate
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createDate = null;

    // @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "update_date")
    @LastModifiedDate
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateDate = null;

    @JsonProperty
    private OperationEnum operation;
}

In this entity i have @ManyToOne mapping but data is saving in only one table.data is not inserting in foreign key column.

So, according to logs there is a NPE returning from this line: if (offerCode == productOffer.getOfferCode() && version == productOffer.getVersion()) actually here offercode 136 available in DB.

Do you have any idea what could be wrong here?

Thanks in advance!


Solution

  • i have used @JsonIgnore at entity class property level.. because of this am unable to fetch id and insert the data into child tables.
    
    Instead of this:
    
        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        @JoinColumn(name = "lcsId")
        @OnDelete(action = OnDeleteAction.CASCADE)
        @JsonIgnore
        private LifeCycleStatus lifecycleStatus = null;
    
    We can have like this:
    
        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
        @JoinColumn(name = "lcsId")
        private LifeCycleStatus lifecycleStatus = null;