How to configure cloud datasource for MySQL on Bluemix? - mysql

How do I create a datasource for cloud in MySQL when running on Bluemix? If there are any Java configuration examples available, please share. How do I make Hibernate create tables and why do I get this error?
Error creating bean with name 'entityManagerFactory' defined in
com.covenant.app.config.root.DatabaseConfig: Unsatisfied dependency
expressed through constructor argument with index 0 of type
[org.springframework.jdbc.datasource.DriverManagerDataSource]: : No
qualifying bean of type
[org.springframework.jdbc.datasource.DriverManagerDataSource] found
for dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}; nested
exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[org.springframework.jdbc.datasource.DriverManagerDataSource] found
for dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations: {}
My database Config class
#Configuration
#Profile("cloud")
#EnableTransactionManagement
public class CloudDatabaseConfig extends AbstractCloudConfig {
#Bean
public DataSource inventoryDataSource() {
return connectionFactory().dataSource("mysql");
}
#Bean(name = "namingStrategy")
public ImprovedNamingStrategy getNamingStrategy(){
ImprovedNamingStrategy namingStrategy = new CDCustomNamingStrategy();
return namingStrategy;
}
#Bean(name="dataSource")
public BasicDataSource dataSource() throws PropertyVetoException {
BasicDataSource bean = new BasicDataSource();
bean.setDriverClassName("com.mysql.jdbc.Driver");
bean.setUrl("jdbc:mysql://localhost:3306/bluemix?useUnicode=true&characterEncoding=UTF-8");
bean.setUsername("root");
bean.setPassword("root");
return bean;
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, ImprovedNamingStrategy ins) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan(new String[]{"com.covenant.app.model"});
entityManagerFactoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("database", "mysql");
jpaProperties.put("hibernate.hbm2ddl.auto", "update");
jpaProperties.put("hibernate.show_sql", "true");
jpaProperties.put("hibernate.format_sql", "true");
jpaProperties.put("hibernate.use_sql_comments", "true");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
jpaProperties.put("hibernate.ejb.naming_strategy", ins);
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
return entityManagerFactoryBean;
}
}
My manifest.yml file on Bluemix:
---
applications:
- name: lordthankyou
path: target/ideals.war
services:
- mysql
env:
SPRING_PROFILES_ACTIVE: cloud
I get the following errors:
Error creating bean with name 'userService': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.covenant.app.dao.UserRepository
com.covenant.app.services.UserService.userRepository; nested exception
is org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'userRepository': Injection of persistence
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [javax.persistence.EntityManagerFactory] is
defined

Finally I got It working I just added an environment variable to activate cloud profile in manifest.yml and removed extends AbstractCloudConfig as it was also searching for mongodb .After these changes It Started working and now I can run spring mvc on blue mix.

Related

JPA non-entity with select database result to List<object[]>

I want to create a REST API for Android using my yii2 fremowork blocking site and its database.
I did not need to create a table in the database, but I would only SELECT and INSERT the information in the desired style.
How can I do this in the Java Spring boot application?
I need to download the information you need
This is my application.properties file
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/uzaart_teda?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
My Service implement class
#Service
public class ProductsServiceimpl implements ProductsService{
#Autowired
ProductsRepository productsRepository;
#Override
public List<ProductsDto> getProducts() {
List<ProductsDto> list=new ArrayList<>();
list.add(new ProductsDto(1,2,"anvar",4,5,6,7));
list.add(new ProductsDto(1,2,"sanjar",4,5,6,7));
/*this is my need --->*/
List<Object[]> objects=productsRepository.selectProducts();
/******/
System.out.println(objects.size());
return list;
}
}
This is my Repository
public interface ProductsRepository extends JpaRepository<Object[],Long> {
#Query(value = "SELECT a.id,a.tovar_id,t.nom_sh,a.kol_ost,a.kol_in_ost, a.opt1 AS sot,a.opt1_in AS sot_in FROM s_tovar t,asos_slave a,asos WHERE a.del_flag=1 AND (asos.tur_oper=1 OR asos.tur_oper=4 OR asos.tur_oper=5) AND a.asos_id=asos.id AND a.tovar_id=t.id AND (a.kol_ost>0 OR a.kol_in_ost>0) AND asos.client_id = 4 AND (((t.nom LIKE \"%0001%\") OR (t.nom LIKE \"%0001%\"))) ORDER BY t.nom,a.srok",nativeQuery = true)
public List<Object[]> selectProducts();
}
My result.
Error message
1.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-07-16 16:20:19.006 ERROR 7328 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controller': Unsatisfied dependency expressed through field 'productsService';
2.
[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
3.
at com.uz.shopapi.ShopApiApplication.main(ShopApiApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'productsServiceimpl':
This is wrong:
public interface ProductsRepository extends JpaRepository<Object[],Long> {
JpaRepository must be of type of class that is annotated with #Entity:
public interface ProductsRepository extends JpaRepository<Product,Long> {
like this:
#Entity
class Product {
…
}
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.multiple-modules.annotations
You have to create entities to use Spring Data JPA, because it needs the entity metadata to create query.
After that, you can use custom object to select result into it.
public interface ProductsRepository extends JpaRepository<Products,Long> {
#Query(select new com.xyt.CustomObject(a.tovar_id,t.nom_sh ... ) from ENTITY1 a, ENTITIY2 t where ...)
public List<CustomObject> selectProducts();
}
Alternatively, you can use simple JDBC template to create sql query with your custom object mapper. In this way you do not need to create those entities.

Jackson Trasformation json data in bean

I have a problem with the transformation of json in bean whene the bean have a date.
The client send, for example, the date 2018-07-13 11:30:00 and jasckson store in the bean the date 2018-07-13 13:30:00.
Can you help me?
I'm using spring-boot 1.5.10 and jackson 1.9.10
Try create a #Configuration class and ad this 2 bean definitions:
#Bean
public JavaTimeModule timeModule(DateTimeFormatter dateTimeFormatter){
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(dateTimeFormatter));
timeModule.addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer(dateTimeFormatter));
return timeModule;
}
#Bean
public ObjectMapper objectMapper(JavaTimeModule timeModule) {
return Jackson2ObjectMapperBuilder.json()
.failOnUnknownProperties(false)
.featuresToEnable(com.fasterxml.jackson.core.JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS)
.featuresToDisable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.modules(timeModule)
.build();
}

Error while Deployment of spring application on JBoss

When I am trying to run my application on jboss, I am getting following stack trace, My application needs database connection at the start of application I am using hibernate, spring integration and my database is mysql. my database details correct. is there anything I am missing ?
2017-01-06 12:12:23,933 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 70) MSC000001:
Failed to start service jboss.undertow.deployment.default-server.default-host./ZealWay:
org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./ZealWay:
java.lang.RuntimeException: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'webController': Unsatisfied dependency expressed through field 'transactionManagerService':
Error creating bean with name 'transactionManagerServiceImpl': Unsatisfied dependency expressed through field 'gatewayFacade':
Error creating bean with name 'gatewayFacade': Unsatisfied dependency expressed through field 'gatewayRouter':
Error creating bean with name 'gatewayRouterImpl': Unsatisfied dependency expressed through field 'gatewayAquirers':
Error creating bean with name 'gatewayAquirers' defined in class path resource [com/iz/zw/configuration/GatewayAquirerConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [java.util.HashMap]: Factory method 'gatewayAquirers' threw exception;
nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction;
nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection;
Datasource configuration code
#Bean
public DataSource dataSource() throws IllegalStateException, PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setJdbcUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUser(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setInitialPoolSize(Integer.parseInt(environment.getProperty("jdbc.initial.pool.size")));
dataSource.setMinPoolSize(Integer.parseInt(environment.getProperty("jdbc.min.pool.size")));
dataSource.setMaxPoolSize(Integer.parseInt(environment.getProperty("jdbc.max.pool.size")));
return dataSource;
}
In your GatewayAquirerConfig you have not defined the bean gatewayAquirers. You probably have:
#Autowired
GatewayAquirers gatewayAquirers;
Somewhere but GatewayAquirers does not have a #Component or #Service or is not being picked up in the package scan.

Spring StateMachine Configuration : Naming StateMachine when using #EnableStateMachineFactory

I would like to include several StateMachine configurations for dynamic instantiation using the StateMachineFactory. But the #EnableStateMachineFactory annotation allows for naming the factory. How does one name each Config (i.e. that extends EnumStateMachineConfigurerAdapter)?
Otherwise, it would be useful to have an example of how to use the setMachineID method within the configuration definition, if that's possible.
Having these enable annotations with Spring `#Configuration' classes simply define bean names which gets registered with application context. Easiest to explained with examples:
#EnableStateMachine
StateMachine as bean stateMachine.
#EnableStateMachine(name = "fooMachine")
StateMachine as bean fooMachine.
#EnableStateMachine(name = {StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, "fooMachine"})
StateMachine as bean stateMachine with bean alias fooMachine.
#EnableStateMachineFactory
StateMachineFactory as bean stateMachineFactory.
#EnableStateMachineFactory(name = "fooMachineFactory")
StateMachineFactory as bean fooMachineFactory.
#EnableStateMachineFactory(name = {StateMachineSystemConstants.DEFAULT_ID_STATEMACHINEFACTORY, "fooMachineFactory"})
StateMachineFactory as bean stateMachineFactory with bean alias fooMachineFactory.
Other than that the name of a #Configuration class(that extends StateMachineConfigurerAdapter) doesn't matter. Thought in Spring a #Configuration class is also created as a bean meaning a below class will exist in Spring Application Context as bean myConfig.MachineFactoryConfig. Just one thing to remember in Spring as badly named class may result bean override!
public class MyConfig {
#Configuration
#EnableStateMachineFactory
public static class MachineFactoryConfig extends StateMachineConfigurerAdapter<String, String> {
}
}
What comes for machineId I just added a new section to docs State Machine ID. (Only in snapshot build until we get next release out)

Spring Security: Java configuration with data source

Not so long ago Spring presented a java based configuration for the Spring Security module. I try to migrate from XML to Java configuration.
Here is my test project: https://github.com/Fruzenshtein/security-spr
pom.xml was updated:
spring.version = 3.2.4.RELEASE
spring.security.version = 3.1.4.RELEASE
...
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-javaconfig</artifactId>
<version>1.0.0.M1</version>
</dependency>
...
<repository>
<id>repository.springsource.milestone</id>
<name>SpringSource Milestone Repository</name>
<url>http://repo.springsource.org/milestone</url>
</repository>
Then I have added a new java config class instead of spring-security.xml
package com.sprsec.init;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.sprsec.service.CustomUserDetailsService;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.userDetailsService(new CustomUserDetailsService())
.authorizeUrls()
.antMatchers("/sec/moderation.html").hasRole("MODERATOR")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/user-login.html")
.defaultSuccessUrl("/success-login.html")
.failureUrl("/error-login.html")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/index.html");
}
}
After that I changed my Initializaer.class to:
package com.sprsec.init;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class Initializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Remark:
spring-security.xml was deleted
A line of code #ImportResource("classpath:spring-security.xml") was deleted in WebAppConfig.java
Filter declaration in web.xml was removed
When I try to run the application on a server I get:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webAppConfig': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.transactionAdvisor()] threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor.setAdvice(Lorg/aopalliance/aop/Advice;)V
Can someone give an advice what can be a reason of this?
You are probably running into some dependency conflict. Run maven dependency:tree to figure out which dependencies are used and find conflicting ones. Also the use of the maven-enforcer-plugin might help.
Looking at your sample project you are using Spring 3.1.3 and the same for Spring Security, you want to have seperate properties for spring and spring security.
<properties>
<hibernate.version>4.1.7.Final</hibernate.version>
<mysql.connector.version>5.1.21</mysql.connector.version>
<slf4j.version>1.6.6</slf4j.version>
<spring.version>3.2.4.RELEASE</spring.version>
<spring.security.version>3.1.4.RELEASE<spring.security.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
As for Spring Security you might want to try out the new 3.2.0.RC1 as that already includes the new spring security javaconfig with improvements and some convenience superclasses.
A final note on your configuration, as that is flawed, you are duplicating your bean instances as you are loading the same configuration twice (duplicating your whole configuration), both the ContextLoaderListener and DispatcherServlet use the WebAppConfig for configuration. This could effectively render your security useless.
Submitted a pull request which should give you some pointers on how to fix the issue at hand.