当前位置: 首页 > 知识库问答 >
问题:

实体对象不在H2数据库中持久化

商绍元
2023-03-14
package com.gasx.corex.scheduler.controller;

import java.awt.*;
import java.util.List;

import com.gasx.corex.scheduler.service.SchedulerJobServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.service.SchedulerJobService;


    @RestController
    @RequestMapping("/gasx/restscd")
    public class SchedulerJobController {

        @Autowired
        private SchedulerJobServiceI schedulerJobService;



        @RequestMapping(method = RequestMethod.POST, value = "/addschedulerjob")
        public void addSchedulerJob(@RequestBody SchedulerJob schedulerJob) {
            schedulerJobService.addSchedulerJob(schedulerJob);
        }

    }
package com.gasx.corex.scheduler.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.rest.SchedulerJobRestRepositoryI;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SchedulerJobService implements SchedulerJobServiceI {

    @Autowired
    private SchedulerJobRestRepositoryI schedulerJobRestRepositoryI;

    @Override
    @Transactional
    public void addSchedulerJob(SchedulerJob schedulerJob) {
        schedulerJobRestRepositoryI.save(schedulerJob);
    }

}
package com.gasx.corex.scheduler.rest;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.ext.user.domain.Profile;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;

@Repository
@Transactional
//@Embeddable
//@RepositoryRestResource(collectionResourceRel = "schedulerJobs", path = "schedulerjobs")
public interface SchedulerJobRestRepositoryI extends CrudRepository<SchedulerJob, Integer> {
    List<Profile> findByName(@Param("name") String name);

}

我的Spring主课:-

package com.gasx.corex.scheduler.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EntityScan(basePackages = "com.gasx.*")
@EnableJpaRepositories(basePackages = {"com.gasx.*"})
//@EnableWebSecurity
@SpringBootApplication(scanBasePackages = { "com.gasx.*" })
@EnableTransactionManagement
@ComponentScan("com.gasx.*" )
public class SchedulerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulerApplication.class, args);
    }

}

我的痛苦。属性

spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:corextrunk;Mode=MySQL;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS corextrunk
spring.datasource.driverclassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
spring.flyway.enabled=true
spring.h2.console.enabled=true
spring.boot.admin.client.enabled=false

我在执行保存函数时的控制台输出:-

不要忘记我的集成测试类:=

package com.gasx.corex.ext.scheduler.integrationtest.domain;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gasx.corex.base.configuration.CoreConfiguration;
import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.ext.scheduler.domain.utils.SchedulerJobType;

import com.gasx.corex.scheduler.rest.SchedulerJobRestRepositoryI;
import com.gasx.corex.scheduler.service.SchedulerJobService;
import com.gasx.corex.scheduler.service.SchedulerJobServiceI;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.http.HttpHeaders;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

import java.util.Base64;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT  , properties = {
        "management.server.port=0", "management.context-path=/admin" ,"security.basic.enabled=false"} )
//@EnableAutoConfiguration
@ContextConfiguration( classes = {AllowAnonymousWebAccess.class  } )
@AutoConfigureMockMvc
@ComponentScan("com.gasx.*")
@TestPropertySource(locations = "classpath:application-testing-h2.properties")
public class SchedulerJobTestInt {

    @LocalServerPort
    private int port  ;

    @Autowired
    private TestRestTemplate testRestTemplate;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void addSchedulerJobIntTest() throws  Exception{
        SchedulerJob schedulerJob = new SchedulerJob();
        schedulerJob.setName("ALB Cleanup");
        schedulerJob.setDescription("Cleanup of alb jobs. Please do not deactivate!");
        schedulerJob.setType(SchedulerJobType.REST);
        schedulerJob.setActive(true);
        schedulerJob.setStartMissedRun(false);
        schedulerJob.setCategory("SYSTEM");
        schedulerJob.setCronExpression(null);
        schedulerJob.setScheme("testScheme");
        schedulerJob.setIdRegion(1);
        schedulerJob.setAlbEndpoint("testAlbEndPoint");
        schedulerJob.setAlbPayload("SCHED_ALB");
        schedulerJob.setAlbPrio(1);
        schedulerJob.setAlbJobUser("MKRAUS");
        schedulerJob.setScriptParams("testScriptParams");
        schedulerJob.setShellScriptParams("clear_tmp 15");
        schedulerJob.setSoapEndpointAlias("");
        schedulerJob.setSoapImportPath("CORE/CORE2003/imp/price");
        schedulerJob.setSoapExportPath("testExportPath");
        schedulerJob.setSoapPayload("<api:readPartnersByIdRequest>");
        schedulerJob.setSoapAction("urn:readPartnersById");
        schedulerJob.setRestEndpointAlias("testEndpointAlias");
        schedulerJob.setRestUrl("testUrl");
        schedulerJob.setRestEntityContent("");
        schedulerJob.setRestExportPath("testRestExportPath");
        schedulerJob.setHookScriptName("testHookScriptName");
        schedulerJob.setMinutes("");
        schedulerJob.setHours("");




        mockMvc.perform(post("/gasx/restscd/addschedulerjob").content(asJsonString(schedulerJob))
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }



}

共有1个答案

海保臣
2023-03-14

控制器:

package com.gasx.corex.scheduler.controller;

import java.awt.*;
import java.util.List;

import com.gasx.corex.scheduler.service.SchedulerJobServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.service.SchedulerJobService;


    @RestController
    @RequestMapping("/gasx/restscd")
    public class SchedulerJobController {

        @Autowired
        private SchedulerJobService schedulerJobService;



        @RequestMapping(method = RequestMethod.POST, value = "/addschedulerjob")
        public void addSchedulerJob(@RequestBody SchedulerJob schedulerJob) {
            schedulerJobService.addSchedulerJob(schedulerJob);
        }

    }

服务:

package com.gasx.corex.scheduler.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.scheduler.rest.SchedulerJobRestRepositoryI;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SchedulerJobService implements SchedulerJobServiceI {

    @Autowired
    private SchedulerJobRestRepositoryI schedulerJobRestRepositoryI;

    @Override
    @Transactional
    public void addSchedulerJob(SchedulerJob schedulerJob) {
        SchedulerJobRestRepositoryI.save(schedulerJob);
    }

}

存储库:

package com.gasx.corex.scheduler.rest;

import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.gasx.corex.ext.scheduler.domain.SchedulerJob;
import com.gasx.corex.ext.user.domain.Profile;

public interface SchedulerJobRestRepositoryI extends JpaRepository<SchedulerJob, Integer> {
    List<SchedulerJob> findByName(@Param("name") String name);
}
spring:
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate: 
      ddl-auto: create-drop
    properties:
      hibernate:
        show-sql: false  
        format_sql: true
        order_inserts: true
        order_updates: true
        jdbc:
          batch_size: 50
  h2:    
    console:
      enabled: false
      settings:
        trace: false
  batch:
    table-prefix: My_
    initializer:
      enabled: false

  datasource:
    url: jdbc:h2:mem:MYBASE;Mode=Oracle;
    platform: h2
    username: sa
    password:
    driverClassName: org.h2.Driver
    continue-on-error: true
@SpringBootApplication
@ComponentScan({
    "fullPackage.controller",
    "fullPackage.service"
    })
@EnableJpaRepositories(basePackages = {
    "fullPackage.repository"     
   })
@EntityScan(basePackages= {
    "fullPackage.entity"
    })
public class SchedulerApplication { 
}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT  , properties = {
        "management.server.port=0", "management.context-path=/admin" ,"security.basic.enabled=false"} )
@ContextConfiguration( classes = {AllowAnonymousWebAccess.class  } )
@AutoConfigureMockMvc // i do not why you use it ?
@DataJpaTest
@TestPropertySource(locations = "classpath:application-testing-h2.properties")
@EntityScan(basePackages = {"fullPackage.entity")
@EnableJpaRepositories(
    basePackages = {"fullPackage.repository"}
public class SchedulerJobTestInt {
...
}
 类似资料:
  • 我的应用程序有3个组件, 1) 一种面向用户的组件,接收请求并将其存储到数据库中。2)一个后端组件,从数据库中读取数据,进行处理并将其发送到外部系统。3) 存储用户输入的数据库 我如何测试流程是这样的:用户输入数据- 注意:我尝试使用ddl auto:update,但它不起作用。

  • 如何使用h2database配置spring boot,以便在每次重新启动时重用数据库。 这是我申请表中唯一的一行。属性文件 spring.jpa.databaseorg.hibernate.dialect.方言

  • 问题内容: 我正在尝试将实体类持久化在数据库中,为此,我尝试了几种针对我的类的实现,但仍然面临错误(但存在不同的错误)。我的实体类现在像这样: 在我的Dao类中,我为我的方法尝试了这两种实现: 和 使用这两个选项时,如果我尝试保存没有属性Pagina或Produto的实体,则该实体将毫无问题地存储在数据库中。但是,如果我尝试使用此属性提交数据,则会遇到问题。 在第一个选项中,将触发异常,在第二个选

  • 我正在使用网络逻辑10.3。我正在尝试配置一个持久订阅,其中包含由 jdbc 存储(在 Oracle DB 中)支持的持久消息。我有一个主题,MDB 正在作为持久订阅者侦听该主题。在场景-1下:如果我发送消息,它会命中MDB。 在场景2中:我挂起了MDB,希望发送到主题的消息只要不被MDB(它是唯一注册的持久订阅者)使用,就会一直存在。但是当我向主题发送消息时,它短暂地出现在那里,然后就消失了(我

  • 我有一个实体CandidateTransaction和CandidateTransactionRepository扩展了CrudRepository 我正在使用CrudRepository的save方法来保存所述实体的对象。当实体没有行时,它将创建一个自动生成的键并将其插入ID列,而不需要Java端的干预。 而且,由于CrudRepository的save()方法检查实体是否是新的,如果是新的,它