无法提交 JPA 事务/提交事务时出错/NullPointerException

问题描述 投票:0回答:3

经过几个小时尝试调试并尝试此站点的解决方案后,我需要帮助

我有 2 个微服务,它们使用 RestTemplate 进行通信

商店服务和类别服务,当我尝试将类别添加到商店时,我收到错误,事情是,我没有对这些方法使用@Transactional,而且我不知道从哪里得到的NullPointerException 因为如果我在实体上单独执行 GET 请求,我会正确获取这些值,但是何时链接它们,会出现错误......该怎么办?

如果我用try catch,返回的结果是正确的,但在控制台中,错误仍然相同

类别:

@Entity
@org.hibernate.annotations.DynamicInsert
@org.hibernate.annotations.DynamicUpdate
@Access(AccessType.FIELD)
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Category {

    @Id
    @SequenceGenerator(name = "category_generator", sequenceName = "CATEGORY_GENERATOR_ID")
    @GeneratedValue(generator = "category_generator")
    @Column(name = "CATEGORY_ID")
    private Long categoryId;

    @Version
    private Long categoryVersion;

    @Embedded
    @AttributeOverrides({@AttributeOverride(name = "descriptionName", column = @Column(name = "CATEGORY_NAME", nullable = false)),
            @AttributeOverride(name = "descriptionAbout", column = @Column(name = "CATEGORY_DESCRIPTION", nullable = false))})
    @Valid
    private Description categoryDescription;

  
    protected Category() {
    }

    public Category(Description categoryDescription) {
        this.categoryDescription = categoryDescription;
    }

    public Long getCategoryId() {
        return categoryId;
    }

    public Description getCategoryDescription() {
        return categoryDescription;
    }

    public void setCategoryDescription(Description categoryDescription) {
        this.categoryDescription = categoryDescription;
    }

 

}

服务类别:

@Service
@Validated
public class CategoryService {

    private final CategoryRepository categoryRepository;
    private final CallingFromCategory callingFromCategoryTo;

    @PersistenceContext
    private EntityManager entityManager;


    @Autowired
    public CategoryService(CategoryRepository categoryRepository, CallingFromCategory callingFromCategoryTo) {
        this.categoryRepository = categoryRepository;
        this.callingFromCategoryTo = callingFromCategoryTo;
    }

    public void createCategory(@Valid Category category) {
        categoryRepository.save(category);
    }

    public Category findCategoryById(@Min(1) Long categoryId) {

        return categoryRepository.findById(categoryId).orElseThrow(() -> new CategoryNotFoundException("We don't have that Category"));
    }

    public Category getCategoryByName(@NotBlank String categoryName) {
        Optional<Category> category = Optional.ofNullable(categoryRepository.getCategoryByCategoryDescription_DescriptionName(categoryName));
        if(category.isPresent())
        {
            return category.get();
        }
        else
        {
            throw new CategoryNotFoundException("sorry bout that");
        }
    }
}

类别控制器:

@RestController
@RequestMapping(value = "/categories")
public class CategoryController {

    private final CategoryService categoryService;

    @Autowired
    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @PostMapping(value = "/createCategory")
    public ResponseEntity<String> createCategory(@RequestBody Category category) {
        categoryService.createCategory(category);
        return ResponseEntity.status(HttpStatus.CREATED)
                .header("Category", "CREATED")
                .body("Category was created!");
    }

    @GetMapping(value = "/{categoryId}")
    public ResponseEntity<Category> getCategoryBy(@PathVariable Long categoryId) {
        return ResponseEntity.status(HttpStatus.FOUND)
                .header("Category Entity", "FOUND")
                .body(categoryService.findCategoryById(categoryId));
    }

    @GetMapping(value = "/projections/{categoryId}")
    List<CategoryProjections.DescriptionOnly> findCategories(@PathVariable Long categoryId) {
        return categoryService.findByCategoryDescription(categoryId);
    }

    @GetMapping(value = "/name/{categoryName}", produces = "APPLICATION/JSON")
    public ResponseEntity<Category> getCategoryByName(@PathVariable String categoryName) {
        return ResponseEntity.status(HttpStatus.FOUND)
                .header("Category name is ", categoryName.toString())
                .body(categoryService.getCategoryByName(categoryName));
    }

商店实体:

@Entity
@org.hibernate.annotations.DynamicInsert
@org.hibernate.annotations.DynamicUpdate
@Access(AccessType.FIELD)
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Store {

    @Id
    @GeneratedValue(generator = "STORE_ID_GENERATOR") //pre insert added values on id
    @Column(name = "STORE_ID", unique = true, updatable = false)
    private Long storeId;

    @Embedded @NotNull
    @Column(nullable = false)
    @AttributeOverrides({@AttributeOverride(name = "locationCity", column = @Column(name = "STORE_LOCATION_CITY")),
    @AttributeOverride(name = "locationCountry", column = @Column(name = "STORE_LOCATION_COUNTRY")),
    @AttributeOverride(name = "locationZipCode.zipCode", column = @Column(name = "STORE_LOCATION_ZIPCODE"))})
    @Valid
    private Location storeLocation;

    @NotBlank
    private String storeName;

    @Enumerated(EnumType.STRING)
    private StoreType storeType;





    //unidirectional
    @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, cascade = CascadeType.PERSIST)
 //   @org.hibernate.annotations.OnDelete(action = OnDeleteAction.CASCADE)
    @JoinColumn(name = "CATEGORY_STORE_ID")
    @NotNull
    private Set<Category> categorySet = new HashSet<>(); // we don't want duplicate categories in our store






    protected Store() {}

    //i initialized associations early
    public Store(Location storeLocation, String storeType, String storeName) {
        this.storeLocation = storeLocation;
        this.storeType = Enum.valueOf(StoreType.class, storeType);
        this.storeName = storeName;
    }

    public Long getStoreId() {
        return storeId;
    }

    public Location getStoreLocation() {
        return storeLocation;
    }

    public void setStoreLocation(Location storeLocation) {
        this.storeLocation = storeLocation;
    }

    public Set<Category> getCategorySet() {
        return categorySet;
    }

    public void setCategorySet(Set<Category> categorySet) {
        this.categorySet = categorySet;
    }

    

    public String getStoreName() {
        return storeName;
    }

    public void setStoreName(String storeName) {
        this.storeName = storeName;
    }

    public StoreType getStoreType() {
        return storeType;
    }

    public void setStoreType(StoreType storeType) {
        this.storeType = storeType;
    }



   


    public void add(@NotNull Category category)
    {
        this.categorySet.add(category);
    }
}

门店服务:

@Service
@Validated
public class StoreService {

    @Autowired
    private final StoreRepository storeRepository;

    @Autowired private CallingOthers callingOthers;

    @PersistenceContext
    private EntityManager entityManager;


    @Autowired
    public StoreService(StoreRepository storeRepository) {
        this.storeRepository = storeRepository;
    }

    public void save(@Valid Store store)
    {
        storeRepository.save(store);
    }

    public Store getStore(@NotNull String storeType) {
        return storeRepository.getStoreByStoreType(StoreType.valueOf(storeType));

    }

    public Store addCategory(String storeType, String category) {
        Store store = getStore(storeType);
        ResponseEntity<Category> category1 = callingOthers.getCategory(category);
     //   System.out.println(category1.getBody().getPromotion().getPromotionSeason().isSeason());


     //   store.getCategorySet().forEach(element -> System.out.println(element.getPromotion().getPromotionSeason()));
        store.add(category1.getBody());
   //     store.getCategorySet().forEach(element -> System.out.println(element.getPromotion().getPromotionSeason()));

        Session session = entityManager.unwrap(Session.class);
        session.update(category1.getBody());
        try {

            storeRepository.save(store);
        }
        catch (Exception ex)
        {
            ex.getCause();
            ex.getStackTrace();
            ex.printStackTrace();
        }
        return getStore(storeType);

    }

    public Store getStoreByStoreName(@NotBlank String storeName)
    {
        Optional<Store> storeOptional = Optional.ofNullable(storeRepository.getStoreByStoreName(storeName));
        return storeOptional.orElseThrow(StoreNotFoundException::new);
    }    
}

商店控制器:

@RestController
@RequestMapping(value = "/store")
public class StoreController {

    private final StoreService storeService;

    @Autowired
    public StoreController(StoreService storeService) {
        this.storeService = storeService;
    }

    @PostMapping(value = "/createStore", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public void createStore(@RequestBody Store store)
    {
        storeService.save(store);
    }

    @GetMapping(value = "/{storeType}")
    public Store getStore(@PathVariable("storeType") String storeType)
    {
        return storeService.getStore(storeType);
    }

    @GetMapping(value = "getStoreByName/{storeName}")
    public Store getStoreByName(@PathVariable String storeName)
    {
        return storeService.getStoreByStoreName(storeName);
    }


    @GetMapping(value = "/addCategory/{storeType}/{category}")
    public Store addCategoryToStore(@PathVariable("storeType") String storeType, @PathVariable ("category") String category)
    {
        return storeService.addCategory(storeType, category);

    }
}

RestTemplate实用类:

@Component
public class CallingOthers {

    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<Category> getCategory(String categoryName)
    {
        return restTemplate.getForEntity("http://localhost:8080/categories/name/"+categoryName, Category.class);
    }
}

堆栈错误跟踪:

ERROR 3984 --- [nio-8080-exec-5] o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during managed flush [null]
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:571)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at com.sun.proxy.$Proxy129.save(Unknown Source)
    at com.balabasciuc.shoppingprojectwithhibernate.StoreModule.Service.StoreService.addCategory(StoreService.java:73)
    at com.balabasciuc.shoppingprojectwithhibernate.StoreModule.Service.StoreService$$FastClassBySpringCGLIB$$30a072fa.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:793)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:123)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708)
    at com.shoppingprojectwithhibernate.StoreModule.Service.StoreService$$EnhancerBySpringCGLIB$$f20a164c.addCategory(<generated>)
    at com.shoppingprojectwithhibernate.StoreModule.Controller.StoreController.addCategoryToStore(StoreController.java:42)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:75)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562)
    ... 76 more
Caused by: java.lang.NullPointerException
    at org.hibernate.type.LongType.next(LongType.java:62)
    at org.hibernate.type.LongType.next(LongType.java:23)
    at org.hibernate.engine.internal.Versioning.increment(Versioning.java:92)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.getNextVersion(DefaultFlushEntityEventListener.java:379)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:275)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:143)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:216)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:85)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3190)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2404)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    ... 77 more
java spring-boot hibernate spring-data-jpa transactions
3个回答
2
投票

终极解决方案

按照给出的错误

...at com.balabasciuc.shoppingprojectwithhibernate.StoreModule.Service.StoreService.addCategory(StoreService.java:73) ...

只需添加

@Transactional(readOnly = true)

服务方法

例如

@Transactional(readOnly = true)
public Store addCategory(String storeType, String category) {...}

注意:此解决方案适用于任何出现错误的服务方法。


1
投票

在这一行中,您将获得一个 Category 对象,确保它具有“categoryId”字段不为空

ResponseEntity<Category> category1 = callingOthers.getCategory(category);

数据库表示需要与映射的内容一致。

Hibernate 只允许未保存的实体具有非空版本。

检查这个


0
投票

我建议交叉检查您的请求正文一次。就我而言,我为模型/实体类中的字段之一提供了注释 @NotNull。在发送 POST 请求时,我忘记在 API 请求正文中添加该字段,因此引发了此错误。

当我最终在请求正文中添加该字段时,我解决了这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.