hibernate multiple database configuration files - spring

I have the database config show below file that reads from the application.properties which has information to connect to a single data base.
I want to add another similar configuration file that will allow me to connect to another database and use its session factory like the primary one I already have.
I am working on making another similar file which reads from another application properties file. However I am not sure how to wire it so that I can have multiple session factories in each of my entity classes
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class DatabaseConfig {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
} // class DatabaseConfig
Usage of session factory in a generic dao. I would like another session factory that can connect to another datasource.
#Repository("baseDao")
#Transactional
public class BaseDaoImpl<T extends Serializable> implements BaseDao<T> {
#Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
...

Related

Spring boot: I need an explanation for a few lines of code

I am studying spring boot, and am failing to understand a few lines of code.
Referring to the code below, I would like to understand what is needed
#ComponentScan ("boot.entry")
and these two lines declared in the transactionManager() method, that is
HibernateTransactionManager txManager = new HibernateTransactionManager ();
txManager.setSessionFactory (sessionFactory (). getObject ());
Can anyone kindly help me?
package config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableTransactionManagement
#EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class})
#ComponentScans(value = { #ComponentScan("boot.entry"),
#ComponentScan("Model"),
#ComponentScan("Controller"),
#ComponentScan("DAO"),
#ComponentScan("Miscallaneous"),
#ComponentScan("Service")})
public class Config {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactory.setHibernateProperties(hibernateProperties);
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver resolver= new InternalResourceViewResolver();
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
#ComponentScan ("boot.entry")
#ComponentScan basically instruct the Spring IoC to track down the entities for dependency injection.
HibernateTransactionManager txManager = new HibernateTransactionManager ();
txManager.setSessionFactory (sessionFactory (). getObject ());
HibernateTransactionManager handles the transaction handling which requires HibernateSession which is basically an instance of datasource wrapped within JPA specification to handle OOP oriented query handling.
#ComponentScan ("boot.entry") Means that It should load all Components (Beans, Services etc) inside the boot.entry package, which probably should be contained in your project.
Hibernate is an ORM library that lets you do SQL queries without writing SQL. What you are doing in your code is basically initializing the transactionManager with the data from the sessionFactory() function.

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException Caused by: java.lang.NullPointerException

I am working on SpringBoot, Hibernate application and when I am trying to the run the application. I am getting error "Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException"
Error log that I am getting:
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.NullPointerException
at com.spring.main.SpringLogging3Application.data(SpringLogging3Application.java:97)
at com.spring.main.SpringLogging3Application.main(SpringLogging3Application.java:53)
... 5 more
Below is the source code that I am trying to run. Just assume that I am having two entity classes Question and Answer with it's getter and setter methods.
import java.util.ArrayList;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})
#ComponentScan("com.spring.main")
public class SpringLogging3Application {
#Autowired
static SessionFactory factory;
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${hibarenate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibarenate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibarenate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TOSCAN;
public static void main(String[] args) {
SpringApplication.run(SpringLogging3Application.class, args);
data();
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource datasource) throws Exception {
Properties hibernateproperties = new Properties();
hibernateproperties.put("hibarenate.dialect", HIBERNATE_DIALECT);
hibernateproperties.put("hibarenate.show_sql", HIBERNATE_SHOW_SQL);
hibernateproperties.put("hibarenate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
LocalSessionFactoryBean factorybean = new LocalSessionFactoryBean();
factorybean.setDataSource(dataSource());
factorybean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TOSCAN);
factorybean.setHibernateProperties(hibernateproperties);
factorybean.afterPropertiesSet();
SessionFactory sf = factorybean.getObject();
System.out.println("##getSessionFactory" +sf);
return sf;
}
#Autowired
#Bean(name="datasource")
public DataSource dataSource() {
DriverManagerDataSource datasources = new DriverManagerDataSource();
datasources.setDriverClassName(DB_DRIVER);
datasources.setUrl(DB_URL);
datasources.setUsername(DB_USERNAME);
datasources.setPassword(DB_PASSWORD);
System.out.println("## getDataSource: " +datasources);
return datasources;
}
#Autowired
#Bean(name="transactrionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionfactory) {
HibernateTransactionManager manager = new HibernateTransactionManager(sessionfactory);
//manager.setSessionFactory(sessionFactory().getObject());
return manager;
}
public static void data() {
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Answer an1=new Answer();
an1.setAnswername("Java is programming language");
an1.setPostedBy("Ravi Malik");
Answer an2=new Answer();
an2.setAnswername("Java is a platform");
an2.setPostedBy("Sudhir Kumar");
Question q1=new Question();
q1.setQuestion("What is Java?");
ArrayList<Answer> l1=new ArrayList<Answer>();
l1.add(an1);
l1.add(an2);
q1.setAnswer(l1);
Answer ans3=new Answer();
ans3.setAnswername("Servlet is an Interface");
ans3.setPostedBy("Jai Kumar");
Answer ans4=new Answer();
ans4.setAnswername("Servlet is an API");
ans4.setPostedBy("Arun");
Question q2=new Question();
q2.setQuestion("What is Servlet?");
ArrayList<Answer> l2=new ArrayList<Answer>();
l2.add(ans3);
l2.add(ans4);
q2.setAnswer(l2);
session.persist(q1);
session.persist(q2);
t.commit();
session.close();
System.out.println("Success");
}
}
Updated code - After implementing commandlineRunner
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class})
#ComponentScan("com.spring.main")
public class SpringLogging3Application implements CommandLineRunner {
SessionFactory factory;
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${hibarenate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibarenate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibarenate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TOSCAN;
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource datasource) throws Exception {
Properties hibernateproperties = new Properties();
hibernateproperties.put("hibarenate.dialect", HIBERNATE_DIALECT);
hibernateproperties.put("hibarenate.show_sql", HIBERNATE_SHOW_SQL);
hibernateproperties.put("hibarenate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
LocalSessionFactoryBean factorybean = new LocalSessionFactoryBean();
factorybean.setDataSource(dataSource());
factorybean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TOSCAN);
factorybean.setHibernateProperties(hibernateproperties);
factorybean.afterPropertiesSet();
SessionFactory sf = factorybean.getObject();
System.out.println("##getSessionFactory" +sf);
return sf;
}
#Autowired
#Bean(name="datasource")
public DataSource dataSource() {
DriverManagerDataSource datasources = new DriverManagerDataSource();
datasources.setDriverClassName(DB_DRIVER);
datasources.setUrl(DB_URL);
datasources.setUsername(DB_USERNAME);
datasources.setPassword(DB_PASSWORD);
System.out.println("## getDataSource: " +datasources);
return datasources;
}
#Autowired
#Bean(name="transactrionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionfactory) {
HibernateTransactionManager manager = new HibernateTransactionManager(sessionfactory);
//manager.setSessionFactory(sessionFactory().getObject());
return manager;
}
public static void main(String[] args) {
SpringApplication.run(SpringLogging3Application.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Inside run method");
Session session = factory.openSession();
Transaction t = session.beginTransaction();
Answer an1=new Answer();
an1.setAnswername("Java is programming language");
an1.setPostedBy("Ravi Malik");
Answer an2=new Answer();
an2.setAnswername("Java is a platform");
an2.setPostedBy("Sudhir Kumar");
Question q1=new Question();
q1.setQuestion("What is Java?");
ArrayList<Answer> l1=new ArrayList<Answer>();
l1.add(an1);
l1.add(an2);
q1.setAnswer(l1);
Answer ans3=new Answer();
ans3.setAnswername("Servlet is an Interface");
ans3.setPostedBy("Jai Kumar");
Answer ans4=new Answer();
ans4.setAnswername("Servlet is an API");
ans4.setPostedBy("Arun");
Question q2=new Question();
q2.setQuestion("What is Servlet?");
ArrayList<Answer> l2=new ArrayList<Answer>();
l2.add(ans3);
l2.add(ans4);
q2.setAnswer(l2);
session.persist(q1);
session.persist(q2);
t.commit();
session.close();
//return "Success";
}
}
The problem is this.
#Autowired
static SessionFactory factory;
You can not auto wire static fields.

NoSuchMethodError Table.indexes() hibernate-core-5.2.13.Final.jar when try to start application?

There is application srping+jpa. Webserver is Websphere 8.5.13
So, I launch application by using WebApplicationInitializer where I add configs.
There is problem when added PersisnteceConfig:
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
#EnableJpaAuditing
#EnableJpaRepositories(basePackages = {"persistence"})
#PropertySource("classpath:application.properties")
#ComponentScan(basePackages = {"persistence"})
public class PersistenceConfig {
private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PACKAGE_WITH_JPA_ENTITIES = "ru.sbrf.risks.services.data.persistence";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";
private static final String DO_NOT_AUDIT_LOCKING_FIELD = "org.hibernate.envers.do_not_audit_optimistic_locking_field";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
System.out.println("1");
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
System.out.println("2");
entityManager.setDataSource(dataSource());
System.out.println("3");
entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
System.out.println("4");
entityManager.setPersistenceProviderClass(HibernatePersistenceProvider.class);
System.out.println("5");
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
System.out.println("6");
entityManager.setJpaProperties(getHibernateProperties());
System.out.println("7");
return entityManager;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
//Set properties hibernate
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
properties.put("hibernate.show_sql", env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));
properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field",
env.getRequiredProperty(DO_NOT_AUDIT_LOCKING_FIELD));
properties.put("verifyServerCertificate", false);
properties.put("useSSL", false);
properties.put("requireSSL", false);
properties.put("useLegacyDatetimeCode", false);
properties.put("useUnicode", "yes");
properties.put("characterEncoding", "UTF-8");
properties.put("serverTimezone", "UTC");
properties.put("useJDBCCompliantTimezoneShift", true);
return properties;
}
}
So,I use hibernate-core-5.2.13.Final libriary and when try to launch application on WebSphere 8.5.13, I have an error message:
Invocation of init method failed; nested exception is
java.lang.NoSuchMethodError:
javax/persistence/Table.indexes()[Ljavax/persistence/Index; (loaded
from
file:/opt/IBM/WebSphere/AppServer/plugins/javax.j2ee.persistence.jar
by org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader#ec08ccb6)
called from class org.hibernate.cfg.annotations.EntityBinder (loaded
from
file:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/MyApp_war.ear/MyApp.war/WEB-INF/lib/hibernate-core-5.2.13.Final.jar
by
com.ibm.ws.classloader.CompoundClassLoader#7f080f2e[war:MyApp_war/MyApp.war]
You're attempting to use a version of Hibernate that implements a different spec version than the JPA 2.0 included in WebSphere 8.5.5. That can be done, but you'll need to bring your own version of the JPA API as well. To do that, you'll either need to switch your web module's class loader to "Parent Last" or move Hibernate and the JPA API jar(s) to a shared library and configure the library to use an isolated class loader (which effectively sets "Parent Last" just for the jars in the library).

ERROR 11664 --- [main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000231: Schema export unsuccessful

I'm trying to get a small project of mine working, regarding the implementation of a process via WebServices.
Problem is: I dont even get to that point because I seem to hit trouble when booting Spring.
Spring is in fact booting but I cant get hibernate working ( atleast I think the problem lies with hibernate? ).
My ErrorLog: onPasteBin
My application.properties:
#New
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
# Hibernate
spring.jpa.hibernate.ddl-auto=create
#Old
# Thymeleaf
spring.thymeleaf.cache: false
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://127.0.0.1:3306/igt
db.username: root
db.password: passwort
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com.entities
And my DatabaseConfig.java:
package com.configs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
public class DatabaseConfig {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
I dont think the Application.java is really relevant to this, but here it is nonetheless:
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Maybe the Project Structure is helpful:
Screenshot of the ProjectStructure
Thanks very much in advance =)

How to provide a parameter value for an autowired variable?

I want to autowire a variable :
package com.ambre.hib.dao;
public interface LangDAO {
public String _getText();
}
package com.ambre.hib.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
public class LangDAOImpl implements LangDAO {
#Autowired
private Environment env;
private String code;
public LangDAOImpl() {
}
public LangDAOImpl(String code) {
this.code = code;
}
#Override
public String _getText() {
return env.getProperty(code);
}
}
package com.ambre.hib.config;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.ambre.hib.dao.LangDAO;
import com.ambre.hib.dao.LangDAOImpl;
import com.ambre.hib.dao.UserDAO;
import com.ambre.hib.dao.UserDAOImpl;
import com.ambre.hib.model.User;
#Configuration
#ComponentScan("com.ambre.hib")
#EnableTransactionManagement
#PropertySource("classpath:lang.properties")
public class ApplicationContextConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer properties() { // managing properties file ( languages )
return new PropertySourcesPlaceholderConfigurer();
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:#localhost:1521:xe");
dataSource.setUsername("system");
dataSource.setPassword("a");
return dataSource;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addAnnotatedClasses(User.class);
return sessionBuilder.buildSessionFactory();
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Autowired
#Bean(name = "userDao")
public UserDAO getUserDao(SessionFactory sessionFactory) {
return new UserDAOImpl(sessionFactory);
}
#Autowired
#Bean(name = "langDAO")
public LangDAO getLangDAO(String code) {
return new LangDAOImpl(code);
}
}
package com.ambre.hib.controller;
... // imports
#Controller
public class HomeController {
#Autowired
private LangDAO langDAO; // how to set here the String "title.home" to the constructor ?
#RequestMapping("/")
public String handleRequest(Model model) throws Exception {
model.addAttribute("titre", langDAO._getText());
return "UserList";
}
}
As you can see I autowired the class LangDAO in the controller. But I want to pass a String as its constructor parameter. How to do that ?
Since I can see that you've already configured the PropertySourcesPlaceholderConfigurer then you can autowire the property from the config file directly to the constructor like so:
#Autowired
public LangDAOImpl(#Value("${you_property_key}") String code) {
this.code = code;
}
or directly on the property
#Value("${you_property_key}") String code
Alternatively, if you define a #PostConstruct method you can get the property from the environment and set it yourself manually.
Values can be autowired in several ways
Spring provides a feature for Autowiring of the system properties.
#Value("${pool.size}")
public String size;
Using spring application context for passing values
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<constructor-arg value="${property.from.file}"/>
</bean>
Properties will be loaded into memory using
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:service.properties</value>
</property>
</bean>
ref: http://www.tutorialspoint.com/spring/spring_autowiring_byconstructor.htm

Resources