Search code examples
javaspring-bootintegration-testingh2in-memory-database

Entity Object not persisting In H2 database


I have implemented integration test for my controller .

and I am trying to test The POST method which creates a new record .

My controller :-

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

    }

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

}

My Repository :-

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

}

My Spring Main 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);
    }

}

My 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

MY Console Output when executing save function:-

Hibernate: insert into scheduler_job (id, active, alb_endpoint, alb_jobuser, alb_payload, alb_prio, category, cron_expr, description, hook_script_name, hours, id_region, minutes, name, rest_endpoint_alias, rest_entity_content, rest_export_path, rest_media_type, rest_method, rest_url, run_archieve_lifespan, scheme, 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, timeout, type) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 2018-12-14 14:34:35.270 INFO 6908 --- [ Thread-4] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' 2018-12-14 14:34:35.277 INFO 6908 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' 2018-12-14 14:34:35.281 INFO 6908 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2018-12-14 14:34:35.296 INFO 6908 --- [ Thread-4] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

My Problem :- I trued numerous examples on google but still I get no error on console ,insert executed but I cant see my record when I try to view the database from browser :- URL I am using for viewing h2 database :- http://localhost:8081/h2-console I even tried changing :-- spring.jpa.hibernate.ddl-auto=create-drop to spring.jpa.hibernate.ddl-auto=create-update ( nonthing changed) removed spring.datasource.platform=h2 from my properties file ,still nothing chnaged .

I am using springBoot and H2 in memory database .

not to forget my Integration test 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());
    }



}

Solution

  • The Controller :

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

    The service :

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

    The repository:

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

    Your application 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
    

    Your Main Class :

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

    Your test 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 {
    ...
    }
    

    Maybe you need some annotations for a personal raison, so you can keep them