SpringBootTest RestController in Spock Test results in 404 - spring-mvc

Given below code for Controller, when I start the spring boot application, I am able to make http calls to the resource /foo/id/{id} to fetch data.
However the same call from an Integration test is returning 404. Call did not trigger rest controller method. Test is not forwarding the http calls to the rest controller. What am I missing?
#RestController
#RequestMapping(“/foo”)
class FooResource {
#RequestMapping(method = RequestMethod.GET, path = “/id/{id}”)
String getData(#PathVariable int id) {
logger.error("===== FooResource.getData called with {}", id)
// more code
}
//more code
//Spock test case
#ContextConfiguration
#SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
#EnableWebMvc
#AutoConfigureWebClient
#TestPropertySource(locations = "classpath:application-test.properties")
class IntegrationTest extends Specification {
#Autowired
RestTemplate restTemplate
#Configuration
#ImportResource(["classpath*:/test-properties.xml", "classpath*:/springintegration-config.xml"])
static class Beans {
#Bean
MessagingTemplate messagingTemplate() { new MessagingTemplate() }
#Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory(9010);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(30 * 1000)
.setReadTimeout(30 * 1000)
.build();
}
}
def ‘foo resource returns the expected data for Id'() {
given:
int id = new SecureRandom().nextInt()
TestRestTemplate restTemplate = new TestRestTemplate();
when:
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:9010/foo/id/1234", String.class)
then:
assert response.statusCode == HttpStatus.OK
}
Test case run log includes the below mappings already available
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/foo/id/{Id}],methods=[GET]}" onto public java.lang.String com.foo.bar.rest.FooResource.getData(int)
2018-06-15 13:54:38.680 DEBUG 20710 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Finished creating instance of bean 'requestMappingHandlerMapping'
2018-06-15 13:54:38.680 DEBUG 20710 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'mvcPathMatcher'
2018-06-15 13:54:38.681 DEBUG 20710 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Creating instance of bean 'mvcPathMatcher'

Changing the Annotations on IntegrationTest class resolved the issue.
//Spock test case
#SpringBootTest(
classes = TestConfig.class,
webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
#AutoConfigureWebClient
#TestPropertySource(locations = "classpath:application-test.properties")
class IntegrationTest extends Specification {
#Autowired
RestTemplate restTemplate
#Configuration
#ImportResource(["classpath*:/test-properties.xml", "classpath*:/springintegration-config.xml"])
static class Beans {
#Bean
MessagingTemplate messagingTemplate() { new MessagingTemplate() }
#Bean
ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory(9010);
}
#Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.setConnectTimeout(30 * 1000)
.setReadTimeout(30 * 1000)
.build();
}
}
def ‘foo resource returns the expected data for Id'() {
given:
int id = new SecureRandom().nextInt()
TestRestTemplate restTemplate = new TestRestTemplate();
when:
ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:9010/foo/id/1234", String.class)
then:
assert response.statusCode == HttpStatus.OK
}

Related

No mapping found for HTTP request with URI [/api/transactions] in DispatcherServlet with name ''

I thought this is a standard configuration. But I get a 404 back. Where else should I configure Spring Boot ?
#RestController
#RequestMapping("/api")
public class TransactionStatisticsController {
public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);
#RequestMapping(value = "/transactions",
method = RequestMethod.POST)
public ResponseEntity sendTransaction(#RequestBody Transaction request) {
logger.info( request.toString());
return new ResponseEntity(HttpStatus.OK);
}
}
This is my test.
#JsonTest
#SpringBootTest(classes = Application.class)
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class TransactionStatisticsRestTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private JacksonTester<Transaction> json;
private static Transaction transaction;
#BeforeClass
public static void createTransaction(){
BigDecimal amount = new BigDecimal(12.3343);
transaction = new Transaction(amount.toString(),
"2010-10-02T12:23:23Z");
}
#Test
public void getTransactionStatus() throws Exception {
final String transactionJson = json.write(transaction).getJson();
mockMvc
.perform(post("/api/transactions")
.content(transactionJson)
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsBytes(transaction);
}
}
Request being made is
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/transactions
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = {"amount":"12.3343000000000007077005648170597851276397705078125","timestamp":"2010-10-02T12:23:23Z[UTC]"}
Session Attrs = {}
Handler:
Type = null
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Update : I added a component scan pointing to a base package. I don't see that error now. Please see the comments where there is an answer.
As in the comment section ,there was only requirement was to bind a component scan base package location .
#Component scan -->Configures component scanning directives for use with #Configuration classes. Provides support parallel with Spring XML's element.
Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Please share your project folder architecture. It might be possible that your controller package is out of the main class package. That's why it is showing 404.
This code :
#RestController
#RequestMapping("/api")
public class TransactionStatisticsController {
public static final Logger logger = LoggerFactory.getLogger(TransactionStatisticsController.class);
#RequestMapping(value = "/transactions",
method = RequestMethod.POST)
public ResponseEntity sendTransaction(#RequestBody Transaction request) {
logger.info( request.toString());
return new ResponseEntity(HttpStatus.OK);
}
}
This should be into your main package where
#SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
this main class resides.
I hope, this will help.
Seems using #JsonTest does not even allow to load Application Context, results mapping is not loaded and its throw 404 so #JsonTest is not a replacement for #SpringBootTest, it is a way to easily test json serialization/de-serialization.
As per documentation:
you can use the #JsonTest annotation. #JsonTest auto-configures the
available supported JSON mapper, which can be one of the following
libraries:
Jackson ObjectMapper, any #JsonComponent beans and any Jackson Modules
Gson
Jsonb
If by using Gson and removing #JsonTest your test run fine..(add Gson Dependency in pom)
#SpringBootTest
#AutoConfigureMockMvc
#RunWith(SpringRunner.class)
public class DemoKj01ApplicationTests {
#Autowired
private MockMvc mockMvc;
private static Transaction transaction;
#BeforeClass
public static void createTransaction(){
BigDecimal amount = new BigDecimal(12.3343);
transaction = new Transaction(amount.toString(),
"2010-10-02T12:23:23Z");
}
#Test
public void getTransactionStatus() throws Exception {
//final String transactionJson = json.write(transaction).getJson();
Gson gson = new Gson();
String jsonRequest = gson.toJson(transaction);
mockMvc
.perform(post("/api/transactions")
.content(jsonRequest)
.contentType(APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
}
It is beacause of the trailing slas in #RequestMapping(value = "/transactions/", method = RequestMethod.POST)
Remove it and it will be ok : value = "/transactions/" => value = "/transactions"

RestTemplateBuilder bean

My application interfaces with different rest endpoints and each one needs a specialized RestTemplate object. I am using RestTemplateBuilder to create each of the RestTemplate objects. Is it ok to clone the RestTemplateBuilder object provided by spring boot and make the changes?
#Configuration
public class Config {
#Bean
public RestTemplate googleRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthorization("user", "pwd123").build();
}
#Bean
public RestTemplate twitterRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.setConnectTimeout(5000).build();
}
}
Here, i get the singleton builder bean injected to both the bean methods. The problem i am trying to overcome is that the mutating of the same builder object. In my example, my 2nd rest template does not need basic authorization but i inadvertently get it.
You can differentiate your RestTemplates using #Qualifier annotation like below.
#Configuration
public class Config {
#Bean
#Qualifier("googleRestTemplate")
public RestTemplate googleRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.basicAuthorization("user", "pwd123").build();
}
#Bean
#Qualifier("twitterRestTemplate")
public RestTemplate twitterRestTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.setConnectTimeout(5000).build();
}
}
Then you can use any of RestTemplate beans in your controllers with these #Qualifiers.
#Autowired
#Qualifier("googleRestTemplate")
private RestTemplate restTemplate;
Why would you do that?
Add a config class:
#Configuration
class Config {
#Bean
#Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
}
inside your Controller that will consume your end-points:
#Autowired
RestTemplate restTempl;
#RequestMapping(value = "/consume", method = RequestMethod.POST)
public void samplePostMethod() {
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<String>("Data", headers);
RequestDetails requestDetails = new RequestDetails("http://localhost:8082/endpoint1", HttpMethod.POST);
ResponseEntity<String> response = restTempl.exchange(requestDetails.getUrl(), requestDetails.getRequestType(),
entity, String.class);
RequestDetails requestDetailss = new RequestDetails("http://localhost:8082/endpoint2", HttpMethod.POST);
ResponseEntity<String> responses = restTempl.exchange(requestDetailss.getUrl(), requestDetailss.getRequestType(),
entity, String.class);
logger.log("{} {}", response, responses);
return response.getBody();
}

Async timeout downloading a large file using StreamingResponseBody on Spring Boot

I'm trying to expose a REST Service which makes available to download a large file streaming, without keeping in memory first. Also I need this to support async calls, if (at least) two users on the same time call this URL should be able both of them to download it.
Application is set up with Spring Boot.
This is what I have on Controller:
#RestController
public class MyController {
private MyService service;
#Autowired
public MyController(MyService service) {
this.service = service;
}
#RequestMapping(
value = "download",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<StreamingResponseBody> downloadAsync() throws IOException {
StreamingResponseBody responseBody = outputStream -> {
service.download(outputStream);
outputStream.close();
};
return ResponseEntity.ok(responseBody);
}
}
This is what I have on Service (download URL is just a sample to test this behavior):
#Service
public class MyService {
private RestTemplate restTemplate;
#Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void download(OutputStream outputStream) {
ResponseExtractor<Void> responseExtractor = clientHttpResponse -> {
InputStream inputStream = clientHttpResponse.getBody();
StreamUtils.copy(inputStream, outputStream);
return null;
};
restTemplate.execute("http://download.thinkbroadband.com/1GB.zip",
HttpMethod.GET,
clientHttpRequest -> {},
responseExtractor);
}
}
In application.yml among others, I have these properties, nothing fancy at all:
server:
port: 9999
context-path: /rest
And this is the JavaConfig file:
#Configuration
public class ApplicationConfig {
#Bean
public RestTemplate restTemplate() {
ClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory(HttpClients.createDefault());
RestTemplate restTemplate = new RestTemplate(requestFactory);
restTemplate.setErrorHandler(new ClientErrorHandler());
return restTemplate;
}
}
When I call this endpoint localhost:9999/rest/download download starts and downloads some MBs but after some time, it stops and this is what gets shown on my console:
2017-03-18 17:11:54.808 INFO --- [nio-9999-exec-1] o.a.c.c.C.[.[.[/rest] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-03-18 17:11:54.811 INFO --- [nio-9999-exec-1] o.s.w.s.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2017-03-18 17:11:54.895 INFO --- [nio-9999-exec-1] o.s.w.s.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 84 ms
2017-03-18 17:12:25.334 ERROR --- [nio-9999-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Async timeout for GET [/rest/download]
2017-03-18 17:12:25.335 WARN --- [nio-9999-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.context.request.async.AsyncRequestTimeoutException
2017-03-18 17:12:25.366 INFO --- [nio-9999-exec-2] o.a.c.c.CoyoteAdapter : Encountered a non-recycled response and recycled it forcedly.
org.apache.catalina.connector.CoyoteAdapter$RecycleRequiredException: null
at org.apache.catalina.connector.CoyoteAdapter.checkRecycled(CoyoteAdapter.java:494) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.http11.Http11Processor.recycle(Http11Processor.java:1627) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.release(AbstractProtocol.java:977) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:869) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434) [tomcat-embed-core-8.5.11.jar:8.5.11]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.11.jar:8.5.11]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_60]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_60]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.11.jar:8.5.11]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_60]
Can anyone help, please ?
Thanks in advance
If you are encountering this issue using Spring-Boot, it is enough to set the following property to a higher value - for example:
spring:
mvc:
async:
request-timeout: 3600000
or
spring.mvc.async.request-timeout = 3600000
It seems that you run into timeout issues on your async task executor. You can configure the desired timeout (and other settings) with a WebMvcConfigurerAdapter. This code should help resolve this problem. Be sure to replace the ellipsis (...) with the desired values.
This example also registers an interceptor that gets called when there's a timeout in case you want some special handling.
#Configuration
#EnableAsync
#EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
#Override
#Bean(name = "taskExecutor")
public AsyncTaskExecutor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(...);
executor.setMaxPoolSize(...);
executor.setQueueCapacity(...);
executor.setThreadNamePrefix(...);
return executor;
}
#Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
/** Configure async support for Spring MVC. */
#Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(AsyncTaskExecutor taskExecutor, CallableProcessingInterceptor callableProcessingInterceptor) {
return new WebMvcConfigurerAdapter() {
#Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(...)
.setTaskExecutor(taskExecutor);
configurer.registerCallableInterceptors(callableProcessingInterceptor);
super.configureAsyncSupport(configurer);
}
};
}
#Bean
public CallableProcessingInterceptor callableProcessingInterceptor() {
return new TimeoutCallableProcessingInterceptor() {
#Override
public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) throws Exception {
log.error("timeout!");
return super.handleTimeout(request, task);
}
};
}
}

Consume SOAP WS in Spring MVC

I'm trying to consume some SOAP web services within a spring boot application. I've imported the ws's stubs and I've followed WebServiceTemplate, as explained here. Unfortunately, when making requests I get an exception:
2017-01-13 12:13:47.146 ERROR 1300 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.oxm.MarshallingFailureException: JAXB marshalling exception; nested exception is javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.SAXException2: no se ha podido canalizar el tipo "com.dashboard.dto.ComprobarSolicitud" como un elemento, porque le falta una anotación #XmlRootElement]] with root cause
The "ComprobarSolicitud" class is the following one:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "comprobarSolicitud", propOrder = {
"username",
"passwd",
"nif",
"fechaDesde",
"fechaHasta",
"cantidad"
})
public class ComprobarSolicitud {
protected String username;
protected String passwd;
protected String nif;
protected String fechaDesde;
protected String fechaHasta;
protected int cantidad;
// ...getters and setters
WebServiceGatewaySupport class:
public class PerClient extends WebServiceGatewaySupport {
private static final Logger log = LoggerFactory.getLogger(PadronClient.class);
public ComprobarSolicitudResponse comprobarSolicitudes(String pNif, LocalDate pFechaInicio, LocalDate pFechaFin){
ComprobarSolicitud request = new ComprobarSolicitud();
// .. set operations to request
ComprobarSolicitudResponse response = (ComprobarSolicitudResponse) getWebServiceTemplate()
.marshalSendAndReceive(
"https://ws.dir.com:8444/PerExterno/perExterno",
request,
new SoapActionCallback("http://service.ws.per.company.com/ExternalWS/comprobarSolicitudResponse"));
return response;
}
}
Configuration class:
#Configuration
public class PerConfiguration {
#Bean
public Jaxb2Marshaller marshaller(){
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.dashboard.dto.per");
return marshaller;
}
#Bean
public PerClient padronClient(Jaxb2Marshaller marshaller){
PerClient client = new PerClient();
client.setDefaultUri("https://ws.dir.com:8444/PerExterno");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
Should I create a custom marshaller? But, how? I've found this, where it's said that in case #XmlRootElement annotation is missing, I should wrap it in an instance of JAXBElement.
Thank you
SOLUTION!
The exception was self-explanatory, and the solution was straightforward, as just PerClient class was necessary to be modified as follows:
public class PerClient extends WebServiceGatewaySupport {
private static final Logger log = LoggerFactory.getLogger(PadronClient.class);
public ComprobarSolicitudResponse comprobarSolicitudes(String pNif, LocalDate pFechaInicio, LocalDate pFechaFin){
ComprobarSolicitud request = new ComprobarSolicitud();
// .. set operations to request
ObjectFactory of = new ObjectFactory();
JAXBElement<ComprobarSolicitud> reqjaxb = of.createComprobarSolicitud(request);
#SuppressWarnings("unchecked")
JAXBElement<ComprobarSolicitudResponse> response = (ComprobarSolicitudResponse) getWebServiceTemplate()
.marshalSendAndReceive(
"https://ws.dir.com:8444/PerExterno/perExterno",
reqjaxb ,
new SoapActionCallback("http://service.ws.per.company.com/ExternalWS/comprobarSolicitudResponse"));
return response.getValue();
}
}

how and why spring container building EntityManagerFactory for persistence unit 'default'?

i am using spring boot and trying to implement multiple datasources using spring jpa.
Problem when i run server then LocalContainerEntityManagerFactoryBean builds JPA container for Default persistence unit .
i have excluded HibernateJpaAutoConfiguration.class from AutoConfiguration so it should not go for Default datasources? atleast thats what my understanding is.
2015-08-28 08:05:35.933 INFO 3764 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2015-08-28 08:05:35.943 INFO 3764 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
this is how i am running my application
#SpringBootApplication
#Configuration
#EnableAutoConfiguration(exclude = { DataSourceTransactionManagerAutoConfiguration.class,
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
public class Application extends SpringBootServletInitializer/*
* implements
* CommandLineRunner
*/{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
This is how first Config file looks like :
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "xx.xx.repository", entityManagerFactoryRef = "blueberryEntityManagerFactory", transactionManagerRef = "blueberryTransactionManager")
#PropertySource("classpath:application.properties")
public class DbConfigBlueBerry {
#Value("${spring.datasourceblueberry.driver-class-name}")
String driverClassName = "";
#Value("${spring.datasourceblueberry.url}")
String url = "";
#Value("${spring.datasourceblueberry.username}")
String userName = "";
#Value("${spring.datasourceblueberry.password}")
String password = "";
#Bean(name = "blueberryEntityManager")
public EntityManager entityManager() {
return entityManagerFactory().createEntityManager();
}
#Bean(name = "blueberryEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(DataSourceBuilder.create().url(url)
.driverClassName(driverClassName).username(userName)
.password(password).build());
factoryBean.setJpaVendorAdapter(jpaVendorAdapter());
factoryBean.setPackagesToScan(R.Blueberry_PACKAGE);
factoryBean.setPersistenceUnitName("blueberryPersistenceUnit");
Properties jpaProperties = new Properties();
factoryBean.setJpaProperties(jpaProperties);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setDatabase(Database.MYSQL);
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setShowSql(true);
return jpaVendorAdapter;
}
#Bean(name = "blueberryTransactionManager")
PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory());
}
Note:
LocalContainerEntityManagerFactoryBean builds entityManagerFactory for my defined datasource as well but after building Default one.
Building JPA container EntityManagerFactory for persistence unit 'blueberryPersistenceUnit'
2015-08-28 08:05:36.925 INFO 3764 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: blueberryPersistenceUnit
...]
My Doubts
whats the significance of Default PersistenceUnitInfo ?
From where it is building the Default PersistenceUnitInfo ? What am i missing ?
Please provide your valuable thoughts. Thanks.

Resources