I have a Jersey Rest Web Service and I would like to send json response removing all fields with null values from json response.
I'm using
#JsonInclude(JsonInclude.Include.NON_NULL)
but it doesn't work at both class and attribute level.
My resource class contain this function:
#RolesAllowed("ADMIN")
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#ApiOperation(value = "test Create", response = TestResponse.class)
public Response Create(TestRequest request, #Context ContainerRequestContext context) {
TestResponse resp = new TestResponse();
resp.setValueA("Value A");
return Response.ok().entity(resp).build();
}
TestResponse class contain:
#ApiModel("TestResponse")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class TestResponse{
#JsonProperty
private String valueA;
#JsonProperty
private String valueB;
#ApiModelProperty(value = "Value A", example = "value A")
public String getValueA(){
return valueA;
}
public SetValueA(String valueA){
this.valueA = valueA;
}
#ApiModelProperty(value = "Value B", example = "value B")
public String getValueB(){
return valueB;
}
public SetValueB(String valueB){
this.valueB = valueB;
}
}
my JSON response contain:
{"valueA":"ValueA","valueB":null}
but I would like to send back this JSON:
{"valueA":"ValueA"}
this is my application class:
#ApplicationPath("/rest")
public class App extends ResourceConfig {
public App() {
packages("it.ivan");
// Register Auth Filter here
register(AuthenticationFilter.class);
register(StartupHandler.class);
register(MultiPartFeature.class);
register(new LoggingFeature(Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME),
Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 10000));
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("Ivan Rest Application");
beanConfig.setVersion("1.0.0");
beanConfig.setBasePath("/rest/");
beanConfig.setResourcePackage("it.ivan");
beanConfig.setScan(true);
register(beanConfig);
register(io.swagger.jaxrs.listing.ApiListingResource.class);
register(io.swagger.jaxrs.listing.SwaggerSerializers.class);
register(io.swagger.jaxrs.config.DefaultJaxrsConfig.class);
Swagger swagger = new Swagger();
swagger.securityDefinition("basicAuth", new BasicAuthDefinition());
new SwaggerContextService().updateSwagger(swagger);
}
}
this is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.ivan</groupId>
<artifactId>TestRest</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>TestRest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jersey.version>2.33</jersey.version>
<slf4j.version>1.7.29</slf4j.version>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20201115</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0-b180830.0359</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
UPDATE... ISSUE SOLVED...
I removed this dependecy:
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
and I added this one:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
I have this configuration class in a maven project:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import lombok.Data;
#Data
#Configuration
public class SmsConfig {
#Value("${sms.domainId}")
private String domainId;
#Value("${sms.gateway.url}")
private String gatewayUrl;
#Value("${sms.cmd}")
private String cmd;
#Value("${sms.login}")
private String login;
#Value("${sms.passwd}")
private String passwd;
}
I have this service class in a Spring project:
Service("smsService")
public class AltiriaSMSRestServiceImpl implements SmsService {
private final SmsConfig smsConfig;
public AltiriaSMSRestServiceImpl(SmsConfig smsConfig) {
this.smsConfig = smsConfig;
}
#Override
public boolean sendSMS(String msg, String to) throws Exception {
...
}
...
}
and this Test:
#ContextConfiguration(classes = { SmsConfig.class })
#RunWith(SpringJUnit4ClassRunner.class)
public class AltiriaSMSRestServiceImplTest {
#Autowired
#Qualifier("smsService")
private AltiriaSMSRestServiceImpl smsService;
#Test
public void testSendSMS() throws Exception {
smsService.sendSMS("this is a test", "+34776498");
}
}
on IntelliJ IDEA it seems that the values on the config class are set correctly
but when I run the test Junit test does not replace placeHolders
5:25:40.009 [main] DEBUG org.springframework.web.client.RestTemplate - Writing [{ "credentials":{"domainId":"${sms.domainId}","login":"${sms.login}","passwd":"${sms.passwd}"},"destination":["32470855126"], "message":{"msg":"this is a test","concat":"true", "encoding":"unicode"} }] as "application/json"
and here my pom.xml:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<artifactId>lombok</artifactId>
<groupId>org.projectlombok</groupId>
<scope>provided</scope>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.14.0</version>
<scope>test</scope>
</dependency>
</dependencies>
#ContextConfiguration(classes = { SmsConfig.class, AltiriaSMSRestServiceImpl.class})
#RunWith(SpringJUnit4ClassRunner.class)
#TestPropertySource(locations="classpath:application.properties")
public class AltiriaSMSRestServiceImplTest {
..
}
I'm writing a jpa repostory example and I'm getting a runtime exception of type UnsatisfiedDependencyException.
Here is my program:
#Configuration
#EnableJpaRepositories(basePackageClasses = { PersonRepository.class, ProfessionRepository.class})
#ComponentScan( basePackageClasses =MyService.class)
public class SpringDataJpa {
public static void main( String[] args ) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringDataJpa.class);
service myService = applicationContext.getBean(MyService.class);
}
}
The service interface:
public interface service {
void add( Person person );
List<Person> getListOfPersons();
}
The implementation that throw the exception:
#Service
public class MyService implements service {
#Autowired
PersonRepository personRepository;
#Override
public void add( Person person ){
System.out.println("saved");
}
#Override
public List<Person> getListOfPersons() {
return null;
}
}
The repositories:
#Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
}
#Repository
public interface ProfessionRepository extends JpaRepository<Profession, Integer> {
}
The exception i'm getting:
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'myService': Unsatisfied dependency
expressed through field 'personRepository'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'personRepository': Post-processing of merged
bean definition failed; nested exception is
java.lang.NoClassDefFoundError: javax/persistence/SynchronizationType
As I checked this discussion, I added the proposed dependencies. My dependencies in the pom.xml file:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
How to solve this error?
My second question is: should we use #EnableJpaRepositories if we use Spring Boot?
a datasource and an entityManagerFactory beans were missing.
To solve my problem i added the followed code in my configuration class:
#Bean
public DataSource firstDataSource (){
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/ride_tracker?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
driverManagerDataSource.setUsername("root");
driverManagerDataSource.setPassword("password");
return driverManagerDataSource;
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("data");
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
You can try the following version, SynchronizationType is available since 2.1.
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
After springbatch integrates the mvc import interface, the transaction is abnormal, and the service layer is injected into the job to execute the transaction problem.
BatchController.class
#RestController
#RequestMapping(value = "/job")
public class BatchController {
private final JobLauncher jobLauncher;
private final Job batchGenerateJob;
#Autowired
public BatchController(JobLauncher jobLauncher, Job batchGenerateJob) {
this.jobLauncher = jobLauncher;
this.batchGenerateJob = batchGenerateJob;
}
#GetMapping(value = "/{cid}")
public AjaxObj batchgenbycid(#PathVariable String cid) {
if (StringUtils.isBlank(cid) || Integer.parseInt(cid) == 0) {
return ResultUtil.fail("请在左侧点击栏目");
}
JobParameters jobParameters = new JobParametersBuilder()
.addString("channelId", cid)
.addString("siteId", Integer.toString(1))
.addString("runtime", "最后执行时间:" + DateFormatUtils.format(new Date(), "yyyy_MM_dd_HH_mm_ss"))
.toJobParameters();
try {
jobLauncher.run(batchGenerateJob, jobParameters);
} catch (JobExecutionAlreadyRunningException e) {
e.printStackTrace();
} catch (JobRestartException e) {
e.printStackTrace();
} catch (JobInstanceAlreadyCompleteException e) {
e.printStackTrace();
} catch (JobParametersInvalidException e) {
e.printStackTrace();
}
return ResultUtil.success();
}
}
** BatchNewsConfig.class **
#Configuration
#EnableBatchProcessing
#EnableTransactionManagement
public class BatchNewsConfig implements StepExecutionListener {
public static final String SITE_ID = "siteId";
public static final String CHANNEL_ID = "channelId";
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final JobRepository jobRepository;
private Map<String, JobParameter> parameterMap;
#Autowired
public BatchNewsConfig(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository) {
this.jobBuilderFactory = jobBuilderFactory;
this.stepBuilderFactory = stepBuilderFactory;
this.jobRepository = jobRepository;
}
#Bean
public JobLauncher jobLauncher() {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return jobLauncher;
}
#Bean
public Job batchGenerateJob() {
return jobBuilderFactory.get("batchGenerateJob")
//获取站点信息
.start(getSiteParameterStep())
.build();
}
#Bean
public Step getSiteParameterStep() {
return stepBuilderFactory.get("getChannelIdParameterStep")
.listener(this)
.tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
String channelStr = parameterMap.get(CHANNEL_ID).toString();
Integer cid = Integer.valueOf(channelStr);
System.out.println(cid);
return RepeatStatus.FINISHED;
}
}).build();
}
#Override
public void beforeStep(StepExecution stepExecution) {
parameterMap = stepExecution.getJobParameters().getParameters();
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
** Console output Can run**
16:37:42,840 INFO SimpleJobLauncher:133 - Job: [SimpleJob: [name=batchGenerateJob]] launched with the following parameters: [{channelId=368, siteId=1, runtime=最后执行时间:2018_12_20_16_37_42}]
16:37:42,913 INFO SimpleStepHandler:146 - Executing step: [getChannelIdParameterStep]
368
16:37:42,950 INFO SimpleJobLauncher:136 - Job: [SimpleJob: [name=batchGenerateJob]] completed with the following parameters: [{channelId=368, siteId=1, runtime:2018_12_20_16_37_42}] and the following status: [COMPLETED]
```
### When I injected the Service, I executed the error again.
** IChannelBatchService **
```java
import cn.dahe.model.Channel;
import java.util.Set;
public interface IChannelBatchService{
Channel get(int id);
Set<Integer> getAllChildrenByCid(int cid);
}
** ChannelBatchService **
import cn.dahe.dao.IChannelDao;
import cn.dahe.model.Channel;
import cn.dahe.service.IChannelBatchService;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
#Service("channelBatchService")
public class ChannelBatchService implements IChannelBatchService {
#Resource
private IChannelDao channelDao;
#Override
public Channel get(int id) {
return channelDao.get(id);
}
#Override
public Set<Integer> getAllChildrenByCid(int cid) {
return getChildrenCid(cid, Sets.newHashSet());
}
/**
* #param cid
* #param cidsSet
*/
private Set<Integer> getChildrenCid(int cid, Set<Integer> cidsSet) {
cidsSet.add(cid);
List<Channel> channels = channelDao.getChannelByPid(cid);
if (channels != null && !channels.isEmpty()) {
for (Channel channel : channels) {
cidsSet.add(channel.getId());
cidsSet = getChildrenCid(channel.getId(), cidsSet);
}
}
return cidsSet;
}
}
add service
#Configuration
#EnableBatchProcessing
#EnableTransactionManagement
public class BatchNewsConfig implements StepExecutionListener {
public static final String SITE_ID = "siteId";
public static final String CHANNEL_ID = "channelId";
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final JobRepository jobRepository;
private final IChannelBatchService iChannelBatchService;
private Map<String, JobParameter> parameterMap;
public BatchNewsConfig(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, JobRepository jobRepository, IChannelBatchService iChannelBatchService) {
this.jobBuilderFactory = jobBuilderFactory;
this.stepBuilderFactory = stepBuilderFactory;
this.jobRepository = jobRepository;
this.iChannelBatchService = iChannelBatchService;
}
#Bean
public JobLauncher jobLauncher() {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(new SimpleAsyncTaskExecutor());
return jobLauncher;
}
#Bean
public Job batchGenerateJob() {
return jobBuilderFactory.get("batchGenerateJob")
.start(getSiteParameterStep())
.build();
}
#Bean
public Step getSiteParameterStep() {
return stepBuilderFactory.get("getChannelIdParameterStep")
.listener(this)
.tasklet(new Tasklet() {
#Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
String channelStr = parameterMap.get(CHANNEL_ID).toString();
Integer cid = Integer.valueOf(channelStr);
System.out.println(cid);
Channel channel = iChannelBatchService.get(cid);
System.out.println(channel);
return RepeatStatus.FINISHED;
}
}).build();
}
/**
* 执行前获取JobParameters
*
* #param stepExecution
*/
#Override
public void beforeStep(StepExecution stepExecution) {
parameterMap = stepExecution.getJobParameters().getParameters();
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
** Console output **
16:48:45,539 INFO JobRepositoryFactoryBean:183 - No database type set, using meta data indicating: MYSQL
16:48:45,674 INFO SimpleJobLauncher:195 - No TaskExecutor has been set, defaulting to synchronous executor.
16:48:45,735 INFO SimpleJobLauncher:133 - Job: [SimpleJob: [name=batchGenerateJob]] launched with the following parameters: [{channelId=368, siteId=1, runtime=2018_12_20_16_48_45}]
16:48:45,792 INFO SimpleStepHandler:146 - Executing step: [getChannelIdParameterStep]
368
16:48:45,811 ERROR AbstractStep:229 - Encountered an error executing step getChannelIdParameterStep in job batchGenerateJob
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#b675ab] for key [{
CreateTime:"2018-12-20 16:48:36",
ActiveCount:2,
PoolingCount:0,
CreateCount:2,
DestroyCount:0,
CloseCount:18,
ConnectCount:20,
Connections:[
]
}] bound to thread [SimpleAsyncTaskExecutor-1]
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:542)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:377)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:461)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy45.get(Unknown Source)
at cn.dahe.batch.BatchNewsConfig$1.execute(BatchNewsConfig.java:88)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:406)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:330)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:272)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:81)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:374)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:144)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:257)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:200)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:148)
at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:392)
at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:306)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#b675ab] for key [{
CreateTime:"2018-12-20 16:48:36",
ActiveCount:2,
PoolingCount:0,
CreateCount:2,
DestroyCount:0,
CloseCount:18,
ConnectCount:20,
Connections:[
]
}] bound to thread [SimpleAsyncTaskExecutor-1]
at org.springframework.transaction.support.TransactionSynchronizationManager.bindResource(TransactionSynchronizationManager.java:190)
at org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:516)
... 26 more
16:48:45,827 INFO SimpleJobLauncher:136 - Job: [SimpleJob: [name=batchGenerateJob]] completed with the following parameters: [{channelId=368, siteId=1, runtime=2018_12_20_16_48_45}] and the following status: [FAILED]
** prom.xml **
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.6</version>
</dependency>
<!-- SPRING -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.16.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.16.RELEASE</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<!-- spring orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.1.3</version>
</dependency>
<!-- AOP begin -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
<scope>runtime</scope>
</dependency>
<!-- AOP end -->
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.1.11.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.1-GA</version>
</dependency>
<!-- LOGGING end -->
<!-- GENERAL UTILS begin -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
<!-- google java library -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<!-- TEST begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.4</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.2.9</version>
</dependency>
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.7.27</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.barcode4j</groupId>
<artifactId>barcode4j-light</artifactId>
<version>2.0</version>
</dependency>
Seems you have multiple transaction managers. In such a case, you can specify the transaction manager for tasklets explicitly.
<tasklet transaction-manager="transactionManager">
#EnableBatchProcessing automatically registers a transaction manager. You can change transaction manager that batch uses simply by implementing the BatchConfigurer interface.
I am trying to use HibernateValidator in SpringMVC tests, but I can't get it to work.
I added it to classpath along with el and validation api deps. In WebMvcConfigurerAdapter overrided getValidator:
#Override
public Validator getValidator() {
LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
validatorFactoryBean.setProviderClass(HibernateValidator.class);
return validatorFactoryBean;
}
Binding result just doesn't have errors that should be produced by hibernate validator, and DTO has null values.
However javax validation annotations works.
What I should to do to make hibernate validator work in
spring mvc tests (with junit runner)?
UPDATE:
Here is how my test looks like:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(classes = {AppConfig.class, WebConfig.class})
public class UserControllerTest {
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
#Before
public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void RegisterUser_ValidData_UserRegistered() throws Exception {
ObjectMapper mapper = new ObjectMapper();
UserRegistrationDTO dto = new UserRegistrationDTO();
String payload = mapper.writeValueAsString(dto);
RequestBuilder request = MockMvcRequestBuilders
.post(URI.create("/users/register"))
.contentType(MediaType.APPLICATION_JSON)
.content(payload);
this.mockMvc.perform(request).andDo...
}
}
Dependencies:
<properties>
<spring.version>4.3.9.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
Controller:
#RestController
#RequestMapping(path = "users", produces = "application/json", consumes = "application/json")
public class UserController {
#PostMapping(path = "/register")
public ResponseEntity register(#Valid #RequestBody UserRegistrationDTO registration) {
return ResponseEntity.ok("registered");
}
}