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

Entity Object not persisting In H2 database

我已经为我的控制器实施了集成测试。

我正在尝试测试创建新记录的 POST 方法。

我的控制器:-

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);
        }

    }

我的服务Class:-

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主要Class:-

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);
    }

}

我的aplication.properties

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

执行保存功能时我的控制台输出:-

Hibernate:插入 scheduler_job (id, active, alb_endpoint, alb_jobuser, alb_payload, alb_prio, category, cron_expr , 描述, hook_script_name, 小时, id_region, 分钟, 姓名, rest_endpoint_alias, rest_entity_content, rest_export_path, rest_media_type, rest_method , rest_url, run_archieve_lifespan, 方案, script_name, script_params, soap_send_action, shell_script_params, soap_action, soap_endpoint_alias, soap_export_path, soap_import_path, soap_payload, start_missed_run, time_control, 超时, 类型) 值 (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?) 2018-12-14 14:34:35.270 INFO 6908 --- [Thread-4] o.s.s.concurrent.ThreadPoolTaskExecutor:关闭 ExecutorService 'applicationTaskExecutor' 2018-12-14 14:34:35.277 INFO 6908 --- [Thread-4] j.LocalContainerEntityManagerFactoryBean:关闭持久性单元的 JPA EntityManagerFactory 'default' 2018-12-14 14:34:35.281 INFO 6908 --- [Thread-4] com.zaxxer.hikari.HikariDataSource:HikariPool-1 - 已启动关机... 2018-12-14 14:34:35.296 INFO 6908 --- [Thread-4] com.zaxxer.hikari.HikariDataSource:HikariPool-1 - 关闭已完成。

我的问题:- 我在 google 上验证了很多例子,但我在控制台上仍然没有错误,插入已执行,但是当我尝试从浏览器查看数据库时我看不到我的记录:- URL 我正在使用查看 h2 数据库 :- http://localhost:8081/h2-console 我什至尝试改变 :-- spring.jpa.hibernate.ddl-auto=create-drop 到 spring.jpa.hibernate.ddl-auto=create-update(无变化) 从我的属性文件中删除了 spring.datasource.platform=h2,仍然没有任何变化。

我在内存数据库中使用springBoot和H2。

别忘了我的集成测试 class :=

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());
    }



}

控制者:

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);
}

您的应用程序 yaml:

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

你的主要 Class :

@SpringBootApplication
@ComponentScan({
    "fullPackage.controller",
    "fullPackage.service"
    })
@EnableJpaRepositories(basePackages = {
    "fullPackage.repository"     
   })
@EntityScan(basePackages= {
    "fullPackage.entity"
    })
public class SchedulerApplication { 
}

你的测试Class:

@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 {
...
}

也许您出于个人原因需要一些注释,所以您可以保留它们