In an spring 4 application I creating two beans as below :
<!-- schemaFactory-->
<bean id="schemaFact" class="javax.xml.validation.SchemaFactory"
factory-method="newInstance">
<constructor-arg value="http://www.w3.org/2001/XMLSchema" />
</bean>
<!-- schema -->
<bean id="schema" class="javax.xml.validation.Schema"
factory-bean="schemaFact" factory-method="newSchema">
<constructor-arg value="classpath:/configs/sample.xsd" />
</bean>
One generates the schema factory and the other uses the factory (to validate xml against xsd).
And in the code:
public class example {
#Inject
private Schema aschema;
......
private validate(){
Validator validator = aschema.newValidator();
validator.validate(xmlFile);
}
}
This works fine, but I wonder if it is possible to write this spring.xml in a way that we don't need to define factory bean separately (and have a simpler spring.xml at the end). As you can see I only need schema bean to be injected in my example class and schemaFact in not needed at all.
Well injected dependencies have to spring beans whether you are using them directly or not.
So even if you are not using SchemaFactory directly in your code but to inject it as dependency in another spring bean, both have to be spring managed beans
You can consider using annotations then you don't need spring file at all.
This is some sample code to create bean in java class. Can create any bean here and autorwired in related class.
This annotations gave us big support to achive it ex- #Configuration
import java.util.Properties;
import javax.persistence.SharedCacheMode;
import........
#Configuration
#ComponentScan(basePackages = {"<package>"})
#EnableTransactionManagement
#PropertySources(value = {#PropertySource(value = {"<property file path>"})})
public class ModulesConfig {
private static final Logger log = LoggerFactory.getLogger(ModulesConfig.class);
#Autowired
private Environment environment;
#Bean(destroyMethod = "close")
public BoneCPDataSource getDataSource() {
BoneCPDataSource dataSource = new BoneCPDataSource();
dataSource.setDriverClass(environment.getProperty("database.driver"));
dataSource.setJdbcUrl(environment.getProperty("database.url"));
dataSource.setUsername(environment.getProperty("database.username"));
dataSource.setPassword(environment.getProperty("database.password"));
dataSource.setIdleConnectionTestPeriodInMinutes(30);
dataSource.setMaxConnectionsPerPartition(5);
dataSource.setMinConnectionsPerPartition(2);
dataSource.setPartitionCount(3);
dataSource.setAcquireIncrement(2);
dataSource.setStatementsCacheSize(100);
return dataSource;
}
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
jpaProperties.setProperty("hibernate.showSql", "false");
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(getDataSource());
em.setPersistenceUnitName("entityManagerFactory");
em.setPackagesToScan("<packages>");
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(jpaProperties);
em.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
return em;
}
#Bean(name = "transactionManager1")
#Primary
public JpaTransactionManager getTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean(name = "transactionManager2")
public JpaTransactionManager getTransactionManager2() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory2().getObject());
return transactionManager;
}
#Bean
#Qualifier("VoucherServiceMarshaller")
public Jaxb2Marshaller getVoucherServiceMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(environment.getProperty("voucher.service.marshaller.contextPath"));
return marshaller;
}
#Bean
#Qualifier("VoucherServiceTemplate")
public WebServiceTemplate getVoucherServiceTemplate() {
WebServiceTemplate template = new WebServiceTemplate(getVoucherServiceMarshaller());
template.setDefaultUri(environment.getProperty("voucher.service.defaultUri"));
return template;
}
#Bean
public VoucherServiceProxy getVoucherServiceProxy() {
VoucherServiceProxy voucherServiceProxy = new VoucherServiceProxy();
return voucherServiceProxy;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public JavaMailSender javaMailSender() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.host", environment.getProperty("mail.smtp.host"));
mailProperties.put("mail.smtp.socketFactory.port", environment.getProperty("mail.smtp.socketFactory.port"));
mailProperties.put("mail.smtp.socketFactory.class", environment.getProperty("mail.smtp.socketFactory.class"));
mailProperties.put("mail.smtp.auth", environment.getProperty("mail.smtp.auth"));
mailSender.setJavaMailProperties(mailProperties);
mailSender.setUsername(environment.getProperty("mail.username"));
mailSender.setPassword(environment.getProperty("mail.password"));
return mailSender;
}
#Bean
public ChargingGatewayServiceProxy getChargingGatewayServiceProxy() {
ChargingGatewayServiceProxy chargingGatewayServiceProxy = new ChargingGatewayServiceProxy();
return chargingGatewayServiceProxy;
}
#Bean
#Qualifier("ChargingGatewayServiceMarshaller")
public Jaxb2Marshaller getChargingGatewayServiceMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(environment.getProperty("cg.service.marshaller.contextPath1"));
return marshaller;
}
#Bean
#Qualifier("ChargingGatewayServiceTemplate")
public WebServiceTemplate getChargingGatewayServiceTemplate() {
WebServiceTemplate template = new WebServiceTemplate(getChargingGatewayServiceMarshaller());
template.setDefaultUri(environment.getProperty("cg.service.url"));
template.setMessageSender(getMessageSender());
return template;
}
#Bean
public HttpComponentsMessageSender getMessageSender() {
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
httpComponentsMessageSender.setConnectionTimeout(Integer.parseInt(environment.getProperty("cg.connection.timeout")));
httpComponentsMessageSender.setReadTimeout(Integer.parseInt(environment.getProperty("cg.read.timeout")));
return httpComponentsMessageSender;
}
#Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(50000);
factory.setConnectTimeout(50000);
return factory;
}
#Bean
public Cache cacheTemp() {
net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();
cm.addCache("cacheTemp");
Cache cache = cm.getCache("cacheTemp");
return cache;
}
#Bean
public Cache cacheActive() {
net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();
cm.addCache("cacheActive");
Cache cache = cm.getCache("cacheActive");
return cache;
}
#Bean
public Cache cache() {
net.sf.ehcache.CacheManager cm = net.sf.ehcache.CacheManager.create().getInstance();
cm.addCache("cache");
Cache cache = cm.getCache("cache");
return cache;
}
}
Related
I having a configuration problem that cause the error below. I know there are a tons of similar problem but I read a lot of answer that stackoverflow suggest with my title but I don't find the right answer yet.
Description:
Field collaborateurJpaRepository in com...infrastructure.persistence.user.UserRepositoryImpl required a bean of type 'com...infrastructure.persistence.jurisdiction.CollaborateurJpaRepository' that could not be found.
Action:
Consider defining a bean of type 'com...infrastructure.persistence.jurisdiction.CollaborateurJpaRepository' in your configuration.
Before to give some details of the code, I think it could be nice that I describe you brievly the context.
I work on a client project which has 8 maven modules (DDD methods) because at the end of the year 4 modules will be separate in an other server.
Recently we create a second oracle database so I had to create multiple configuration to refer to the good dataSource.
I think the problem is due to bad datasource configuration that block the bean spring instanciation.
We are using spring boot version 1.5.7.release.
First Infrastructure configuration
#Configuration
#ComponentScan(basePackages = "com...jade")
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "jadeEntityManager", transactionManagerRef = "jadeTransactionManager")
#EntityScan(basePackages = { "com...jade", "org.springframework.data.jpa.convert.threeten" })
#Profile({"ARA_JADE_CONF", "LOCAL_JADE_CONF"})
public class InfrastructureConfig {
private final static int JDBC_FETCH_SIZE = 1000;
#Autowired
private Environment environment;
#Bean
public LocalContainerEntityManagerFactoryBean jadeEntityManager() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSourceJade());
em.setPackagesToScan(new String[] {"com...jade"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
#Primary
public OracleDataSource dataSourceJade() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(environment.getProperty("db.datasource.jade.username"));
dataSource.setPassword(environment.getProperty("db.datasource.jade.password"));
dataSource.setURL(environment.getProperty("db.datasource.jade.url"));
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean(name="jdbcTemplateJade")
public JdbcTemplate jdbcTemplateJade() throws SQLException {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceJade());
jdbcTemplate.setResultsMapCaseInsensitive(true);
jdbcTemplate.setFetchSize(JDBC_FETCH_SIZE);
return jdbcTemplate;
}
#Bean
public PlatformTransactionManager transactionManager() throws SQLException{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(jadeEntityManager().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
} ...
Seconde Infrastructure configuration
#Configuration
#ComponentScan(basePackages = "com.bnpparibas.sit.risk.art")
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "artEntityManager", transactionManagerRef = "artTransactionManager")
#EntityScan(basePackages = { "com...art", "org.springframework.data.jpa.convert.threeten" })
#Profile({"LOCAL_ART_CONF,'ARA_ART_CONF"})
public class ArtInfrastructureConfig {
private final static int JDBC_FETCH_SIZE = 1000;
#Autowired
private Environment environment;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean artEntityManager() throws SQLException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSourceArt());
em.setPackagesToScan(new String[] {"com...art.infrastructure.persistence"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
#Primary
public OracleDataSource dataSourceArt() throws SQLException {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setUser(environment.getProperty("db.datasource.art.username"));
dataSource.setPassword(environment.getProperty("db.datasource.art.password"));
dataSource.setURL(environment.getProperty("db.datasource.art.url"));
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager artTransactionManager()throws SQLException{
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(artEntityManager().getObject());
return transactionManager;
}
#Bean
#Primary
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}...
Interface link to Entity.
#DDD.Repository
#Repository
public interface CollaborateurJpaRepository extends CrudRepository<Collaborateur,String>{
#Query("FROM ART_PARAM.ART_USER u WHERE u.refogUID = :uid")
Collaborateur findCollaborateurById(#Param("uid") String uid);
}
Class that contain the autowired interface to retrieve some data of the second database.
#DDD.RepositoryImpl
#Repository
#Primary
public class UserRepositoryImpl implements UserRepository {
#Autowired
private CollaborateurJpaRepository collaborateurJpaRepository;
#Override
//#Cacheable(cacheNames = CacheConfig.CACHE_JURIDICTION, key = CacheConfig.CACHE_KEY_UTILISATEUR_ID)
#Transactional("entityManagerFactoryArt")
public User retrieveUser(UserId userId) {
if(userId.getValue() == null) {
return null;
} else {
Collaborateur collaborateur = collaborateurJpaRepository.findOne(userId.getValue());
return new User(collaborateur.getRefogUID(),collaborateur.getRefogFirstName(),collaborateur.getRefogLastName(),collaborateur.getProfile(),collaborateur.isActiveUser(),collaborateur.isBankingSecrecy());
}
}
I have a config class:
#SpringBootConfiguration
#ComponentScan(basePackages = "vap")
public class AppConfig {
Logger logger = LoggerFactory.getLogger(this.getClass());
public AppConfig() {
}
#Bean
public ServerRuntime runtime() {
ServerRuntime runtime = ServerRuntime.builder().addConfig("cayenne-project.xml").build();
return runtime;
}
#Bean
public ObjectContext getContext(#Autowired ServerRuntime serverRuntime) {
return serverRuntime.newContext();
}
#Bean(name = "pgDataSource")
public DataSource getDataSource() {
Properties props = new Properties();
props.setProperty("user", "postgres");
props.setProperty("password", "");
PoolConfiguration configuration = new PoolProperties();
configuration.setDbProperties(props);
configuration.setUrl("jdbc:postgresql://localhost/mikro00");
configuration.setDriverClassName("org.postgresql.Driver");
DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(configuration);
return dataSource;
}
#Bean(name = "hsqldbDataSource")
public DataSource getHSQLDataSource() {
Properties props = new Properties();
props.setProperty("user", "sa");
props.setProperty("password", "");
PoolConfiguration configuration = new PoolProperties();
configuration.setDbProperties(props);
configuration.setUrl("jdbc:h2:file:./outbase");
configuration.setDriverClassName("org.h2.Driver");
DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(configuration);
return dataSource;
}
}
my PGConfig.java
#Configuration
#EnableTransactionManagement
public class PGConfig {
#Primary
#Bean(name = "entityManagerFactoryPG")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, #Qualifier(value = "pgDataSource") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean vap = builder.dataSource(dataSource)
.packages("vap")
.build();
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
vap.setJpaVendorAdapter(jpaVendorAdapter);
return vap;
}
#Primary
#Bean(name = "transactionManagerPG")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
My H2Config.java
#Configuration
#EnableTransactionManagement
public class H2Config {
#Primary
#Bean(name = "dataSource")
#ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, #Qualifier(value = "hsqldbDataSource") DataSource dataSource){
LocalContainerEntityManagerFactoryBean vap = builder.dataSource(dataSource)
.packages("vap")
.build();
JpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
vap.setJpaVendorAdapter(jpaVendorAdapter);
return vap;
}
#Primary
#Bean(name = "transactionManagerH2")
public PlatformTransactionManager transactionManager(
#Qualifier("entityManagerFactory") EntityManagerFactory
entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
KlientRepository
#Repository
public interface KlientRepository extends CrudRepository<Klient,Integer> {
}
How can I read Klient from one repository and write to another. I need to read from PG, work with data and save to h2. I can't find how two object of repository with different datasource, or simply create repository object with concrete datasource
You have pretty much everything out there in your code, you only need to do a bit of fine tuning thats all
Create two configuration classes with bean declaration for Datasource, EntityManagerFactory and TransactionManager
Mark one of the two as primary
Create two model classes(one for each database model)
Create two Repository classes in two different package**(very Important)**
In your service class Autowire both Repositories, read from one DB, manipulate and save to other.
Only thing missing in your code is you need to tell Spring which Repository class should use which EntityManager /Datasource(Since you have two). This can be done by Annotation #EnableJpaRepositories(basepackages=...). Use this annotation on each configuration classes, with basePackages indicating your repository classes
I started out with this guide, to migrate our xml config to an annotation config.
The current problem is, that my test a persist seems to not actually write the data (= no transaction commit). This results in the next check to fail. The environment currently has five persistence units and according entityManagerFactories and transactionManagers.
MyTest.java
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {PersistenceJPAConfig.class}, loader = AnnotationConfigContextLoader.class)
public class MyTest {
#Autowired
private MyDao testable;
#Transactional(transactionManager = "tm1") // tried with name= and without
#Test
public void crudTest() throws Exception {
// assert that the table is empty
List<MyDO> all = testable.getAll();
assertTrue(all.isEmpty());
// write one entity
MyDO anEntity = new MyDO();
testable.persist(anEntity);
// load all entities and assert that the details match
List<MyDO> allAfterInsert = testable.getAll();
// THIS FAILS
assertFalse("The database result should not be empty.", allAfterInsert.isEmpty());
}
}
PersistenceJPAConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScan("my.package")
public class PersistenceJPAConfig {
#PersistenceContext(unitName = "myPersistenceUnit") // also tried
#Bean(name = "myEntityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] {"my.package"});
em.setPersistenceUnitName("myPersistenceUnit");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
// ... the same for the other persistenceUnits with increasing names
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
#Bean(name = "tm1")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getNativeEntityManagerFactory());
transactionManager.setPersistenceUnitName("myPersistenceUnit");
transactionManager.afterPropertiesSet();
return transactionManager;
}
// ... the same for the other persistenceUnits with increasing names
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() {
return new PersistenceAnnotationBeanPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return properties;
}
}
MyDao.java
public class MyDao {
#PersistenceContext(unitName = "myPersistenceUnit")
EntityManager em;
#Override
#Transactional(transactionManager = "tm1") // also tried with different variations like above
public Long persist(final MyDO entity) {
em.persist(entity); // tried to add an em.flush(), but that throws a TransactionRequiredException: no transaction is in progress
// handling transactions would throw IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
return entity.getId();
}
}
The persistence units are located in the file META-INF/persistence.xml.
The tests worked with the xml configuration, but don't work with my current annotation config. Is there something I forgot? What more information could I provide?
I found a solution: Instead of entityManagerFactory().getNativeEntityManagerFactory() I used entityManagerFactory().getObject() and everything works as expected.
#Bean(name = "tm1")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
transactionManager.setPersistenceUnitName("myPersistenceUnit");
transactionManager.afterPropertiesSet();
return transactionManager;
}
I am not sure why though.
I have gone through different resources but still I am not getting my work done. Here is my Spring annotation based configuration :-
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence-mysql.properties" })
#ComponentScan({ "org.baeldung.persistence" })
public class PersistenceJPAConfig {
#Autowired
private Environment env;
public PersistenceJPAConfig() {
super();
}
// beans
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers",
// "true");
return hibernateProperties;
}
}
I have my controller class in org.baeldung.persistence.controller package and denoted #Controller at the top of the class. Still I am getting 404 error when I access the URL /products. Here is my controller class
#Controller
public class ProductViewController {
#RequestMapping(value = "/products", method = RequestMethod.POST)
public String create(#ModelAttribute("product") final Product product) {
final ProductServiceImpl productServiceImpl = new ProductServiceImpl();
if (productServiceImpl.create(product)) {
return "Product with product name : " + product.getProduct_name() + "Has been created";
} else {
return "Error while creating the product record";
}
}
Sinnce your controller class is in org.baeldung.persistence.controller package, you have to scan components in this package
#ComponentScan({ "org.baeldung.persistence.controller" })
you will also need to add #EnableWebMvc in PersistenceJPAConfig class
#EnableWebMvc
I am working on one enhancement in my application. This application is Spring Hibernate implementation.But the enhancement now I am working is Spring-JPA.
Without disturbing the existing implementation I need to include JPA
Below is my DBconfiguration class.
#Configuration
#EnableJpaRepositories(basePackages = {"packagename","package name" })
#EnableTransactionManagement
public class DataBaseConfiguration {
#Value("${postgres.driver}")
private String postgresDriver;
#Value("${postgres.url}")
private String postgresUrl;
#Value("${postgres.username}")
private String postgresUsername;
#Value("${postgres.password}")
private String postgresPassword;
#Value("${hibernate.dialect}")
private String hibernateDialect;
#Value("${hibernate.dialect.property}")
private String dialectProperty;
#Value("${hibernate.show-sql}")
private String hibernateShowSql;
#Value("${boolean.true}")
private String booleanTrue;
**\\ existing hibernate flow**
#Autowired
#Bean(name = "name")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(
dataSource);
sessionBuilder.addAnnotatedClasses(entity.class);
sessionBuilder.setProperty(hibernateDialect, dialectProperty);
sessionBuilder.setProperty(postgresDriver, postgresUrl);
sessionBuilder.setProperty(hibernateShowSql, booleanTrue);
return sessionBuilder.buildSessionFactory();
}
**\\ existing hibernate flow**
#Bean(name = "name")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(postgresDriver);
dataSource.setUrl(postgresUrl);
dataSource.setUsername(postgresUsername);
dataSource.setPassword(postgresPassword);
return dataSource;
}
**\\ existing hibernate flow**
#Autowired
#Bean(name = "manager")
public HibernateTransactionManager getTransactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = null;
transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
**\\included newly for JPA**
#Bean
public org.springframework.orm.jpa.JpaTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(getDataSource());
jpaTransactionManager
.setJpaDialect(new org.springframework.orm.jpa.vendor.HibernateJpaDialect());
return jpaTransactionManager;
}
**\\included newly for JPA**
#Bean
public EntityManager entityManger() {
return entityManagerFactory().getObject().createEntityManager();
}
\\included newly for JPA
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(getDataSource());
entityManagerFactory.setPackagesToScan(
"some package",
"some package");
Map<String, Object> jpaProperty = entityManagerFactory
.getJpaPropertyMap();
jpaProperty.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
va.setShowSql(Boolean.valueOf("true"));
entityManagerFactory.setJpaVendorAdapter(va);
return entityManagerFactory;
}
}
When I deployed this application i am getting below exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class ------
Caused by: java.lang.NullPointerException
at org.hibernate.hql.internal.antlr.HqlBaseParser.identPrimary(HqlBaseParser.java:4285)
at org.hibernate.hql.internal.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:980)
at org.hibernate.hql.internal.antlr.HqlBaseParser.atom(HqlBaseParser.java:3609)
at org.hibernate.hql.internal.antlr.HqlBaseParser.unaryExpression(HqlBaseParser.java:3387)
at org.hibernate.hql.internal.antlr.HqlBaseParser.multiplyExpression(HqlBaseParser.java:3259)
at org.hibernate.hql.internal.antlr.HqlBaseParser.additiveExpression(HqlBaseParser.java:2964)
at org.hibernate.hql.internal.antlr.HqlBaseParser.concatenation(HqlBaseParser.java:597)
at org.hibernate.hql.internal.antlr.HqlBaseParser.relationalExpression(HqlBaseParser.java:2730)
at org.hibernate.hql.internal.antlr.HqlBaseParser.equalityExpression(HqlBaseParser.java:2591)
at org.hibernate.hql.internal.antlr.HqlBaseParser.negatedExpression(HqlBaseParser.java:2555)
at org.hibernate.hql.internal.antlr.HqlBaseParser.logicalAndExpression(HqlBaseParser.java:2471)
at org.hibernate.hql.internal.antlr.HqlBaseParser.logicalOrExpression(HqlBaseParser.java:2436)
at org.hibernate.hql.internal.antlr.HqlBaseParser.expression(HqlBaseParser.java:2146)
at org.hibernate.hql.internal.antlr.HqlBaseParser.exprList(HqlBaseParser.java:3994)
at org.hibernate.hql.internal.antlr.HqlBaseParser.identPrimary(HqlBaseParser.java:4278)
I would suggest another approach, which could be simpler. Make JPA leading and use the LocalContainerEntityManagerFactoryBean to configure everything (including what you use now for hibernate). Next use the HibernateJpaSessionFactoryBean to expose the underlying SessionFactory.
This would save you duplicate configuration and would allow you to use a single JpaTransactionManager for all your transactions, however you still would be able to use a SessionFactory or HibernateTemplate if you would.
#Configuration
#EnableJpaRepositories(basePackages = {"packagename","package name" })
#EnableTransactionManagement
public class DataBaseConfiguration {
#Autowired
private Environment env;
#Autowired
#Bean(name = "name")
public FactoryBean<SessionFactory> getSessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
**\\ existing hibernate flow**
#Bean(name = "name")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getRequiredProperty("postgres.driver"));
dataSource.setUrl(env.getRequiredProperty("postgres.url);
dataSource.setUsername(env.getRequiredProperty("postgres.username");
dataSource.setPassword(env.getRequiredProperty("postgres.password");
return dataSource;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setDataSource(getDataSource());
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
return jpaTransactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(getDataSource());
Map<String, String> properties = new HashMap<String, String>();
properties.put("hibernate.current_session_context_class", SpringSessionContext.class.getName());
entitytManagerFactory.setJpaPropertyMap(properties);
entityManagerFactory.setPackagesToScan(
"some package",
"some package");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
va.setShowSql(env.getProperty("hibernate.show-sql", Boolean.class, true);
va.setDatabasePlatform(env.getProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
entityManagerFactory.setJpaVendorAdapter(va);
return entityManagerFactory;
}
}