This is data source conf. file which has tow data sources. I want to use both of them in DAO class but now only the first data source is working. How can i use both of them ? May be they must be setted in the constructor of dao class or reused with getJdbcTemplate()
public class DataSourceConfig {
// datasource
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://url");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
#Bean
public DataSource dataSourceSecond() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://url");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
// set jdbc template
#Bean
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource());
}
#Bean
public JdbcTemplate jdbcTemplateSecond() {
return new JdbcTemplate(dataSourceSecond());
}
// transaction manager
#Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
#Bean
public TransactionTemplate transactionTemplate() {
return new TransactionTemplate(dataSourceTransactionManager());
}
}
dao
#Repository
public class UsersDao extends JdbcDaoSupport {
#Autowired
private MessageSourceAccessor msa;
#Autowired
public UsersDao(JdbcTemplate jdbcTemplate) {
setJdbcTemplate(jdbcTemplate);
}
public void deleteUser(int userId) {
String sql = msa.getMessage("sql");
Object[] args = new Object[] { userId };
getJdbcTemplate().update(sql, args);
}
}
You can do that with using #Qualifier annotation.
Assuming you want to inject both the jdbcTemplates in a particular class
#Repository
public class MyDao extends JdbcDaoSupport {
#Autowired
public MyDao(#Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate,
#Qualifier("jdbcTemplateSecond") JdbcTemplate jdbcTemplateSecond) {
//code
}
}
Related
This i my database configuration and app.properties
#Configuration
public class DatabaseConfig {
#Bean
#ConfigurationProperties(prefix = "datasource.two")
public HikariConfig hikariConfig2() {
return new HikariConfig();
}
#Bean
public DataSource dataSource2() {
HikariDataSource hds = new HikariDataSource(new hikariConfig2());
return hds;
}
#Bean
public JdbcTemplate jdbcTemplate2() {
return new JdbcTemplate(dataSource2());
}
#Bean
#ConfigurationProperties(prefix = "datasource.one")
public HikariConfig hikariConfig2() {
return new HikariConfig();
}
#Bean
public DataSource dataSource1() {
HikariDataSource hds = new HikariDataSource(hikariConfig1());
return hds;
}
#Bean
public JdbcTemplate jdbcTemplate1() {
return new JdbcTemplate(dataSource1());
}
}
and
datasource.one.jdbc-url=...
datasource.one.username=...
datasource.one.password=...
datasource.one.driver-class-name=...
datasource.two.jdbcUrl=...
datasource.two.username=...
datasource.two.password=...
datasource.two.driver-class-name=...
How should I create global transaction manager which will support two phase commit. I want to run this app inside docker with Tomcat so no JavaEE.
Also no hibernate. I am using sql-processor with spring-stack:
PS: In some very old article I found this but idk if it rigth sollution
#Bean
public DataSourceTransactionManager tm1() {
DataSourceTransactionManager txm = new DataSourceTransactionManager(refDataSource());
return txm;
}
#Bean
public DataSourceTransactionManager tm2() {
DataSourceTransactionManager txm = new DataSourceTransactionManager(logDataSource());
return txm;
}
#Bean(name = "transactionManager")
#Primary
public PlatformTransactionManager transactionManager() throws Throwable {
return new ChainedTransactionManager(tm1(), tm2());
}
I am working on spring boot multi tenancy application. I have configured multi datasources as shown below :
application.properties
spring.multitenancy.datasource1.url=jdbc:mysql://localhost:3306/db1
spring.multitenancy.datasource1.username=root
spring.multitenancy.datasource1.password=****
spring.multitenancy.datasource1.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.multitenancy.datasource2.url=jdbc:mysql://localhost:3306/db2
spring.multitenancy.datasource2.username=root
spring.multitenancy.datasource2.password=****
spring.multitenancy.datasource2.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.multitenancy.datasource3.url=jdbc:mysql://localhost:3306/db3
spring.multitenancy.datasource3.username=root
spring.multitenancy.datasource3.password=****
spring.multitenancy.datasource3.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
DataSourceBasedMultiTenantConnectionProviderImpl.java
#Component
public class DataSourceBasedMultiTenantConnectionProviderImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl {
private static final long serialVersionUID = 8168907057647334460L;
private static final String DEFAULT_TENANT_ID = "tenant_1";
#Autowired
private DataSource dataSource1;
#Autowired
private DataSource dataSource2;
#Autowired
private DataSource dataSource3;
private Map<String, DataSource> map;
#PostConstruct
public void load() {
map = new HashMap<>();
map.put("tenant_1", dataSource1);
map.put("tenant_2", dataSource2);
map.put("tenant_3", dataSource3);
}
#Override
protected DataSource selectAnyDataSource() {
return map.get(DEFAULT_TENANT_ID);
}
#Override
protected DataSource selectDataSource(String tenantIdentifier) {
return map.get(tenantIdentifier);
}
}
MultitenancyProperties.java
#ConfigurationProperties("spring.multitenancy")
public class MultitenancyProperties {
#NestedConfigurationProperty
private DataSourceProperties datasource1;
#NestedConfigurationProperty
private DataSourceProperties datasource2;
#NestedConfigurationProperty
private DataSourceProperties datasource3;
public DataSourceProperties getDatasource1() {
return datasource1;
}
public void setDatasource1(DataSourceProperties datasource1) {
this.datasource1 = datasource1;
}
public DataSourceProperties getDatasource2() {
return datasource2;
}
public void setDatasource2(DataSourceProperties datasource2) {
this.datasource2 = datasource2;
}
public DataSourceProperties getDatasource3() {
return datasource3;
}
public void setDatasource3(DataSourceProperties datasource3) {
this.datasource3 = datasource3;
}
}
MultiTenancyJpaConfiguration.java
#Configuration
#EnableConfigurationProperties(JpaProperties.class)
public class MultiTenancyJpaConfiguration {
#Autowired
private DataSource dataSource;
#Autowired
private JpaProperties jpaProperties;
#Autowired
private MultiTenantConnectionProvider multiTenantConnectionProvider;
#Autowired
private CurrentTenantIdentifierResolver currentTenantIdentifierResolver;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
Map<String, Object> hibernateProps = new LinkedHashMap<>();
hibernateProps.putAll(jpaProperties.getHibernateProperties(dataSource));
hibernateProps.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE);
hibernateProps.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider);
hibernateProps.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver);
hibernateProps.put(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");
return builder.dataSource(dataSource).packages(HotelEntity.class.getPackage().getName()).properties(hibernateProps).jta(false).build();
}
}
Application launcher
#SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
#EnableConfigurationProperties(MultitenancyProperties.class)
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
When I run the boot application, all tables are created in only first data source.
1) How can I create tables in all data sources on application startup?
2) How to see connections opened/closed for each of the data sources?
3) Is there a better way of configuring multi tenancy application using spring boot for better performance?
As #Alex said, you need differnt EntityManagers, TransactionManager and Datasources. Here is how I would do it
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "dataSource1EntityManagerFactory",
transactionManagerRef = "dataSource1TransactionManager",
basePackageClasses = dataSource1Repository.class)
public class DataSource1Config extends SqlConfig{// Put all common code in base class SqlConfig. If not remove it
#Bean
#Primary
public DataSource dataSource1() {
//create dataSource using MultitenancyProperties::getDataSource1
}
#Primary
#Bean(name = "dataSource1TransactionManager")
PlatformTransactionManager dataSource1TransactionManager(EntityManagerFactory dataSource1EntityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(dataSource1EntityManagerFactory);
return txManager;
}
#Primary
#Bean(name = "dataSource1EntityManagerFactory")
LocalContainerEntityManagerFactoryBean dataSource1EntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource1());
em.setPackagesToScan(dataSource1Repository.class.getPackage().getName(), dataSource1ModelClass.class.getPackage().getName());
em.setPersistenceUnitName("dataSource1Db");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
}
You can create two other classes like this. Remember to use #Primary on only one instace of datasource, transactionmanger and entitymanager(doesn't matter which one). Another word of caution, make sure Repository classes are in different packages for all three databases.
Try adding the following properties:
spring.jpa.generate-ddl=true
You need 2 different persistence factories, not one, each should produce different EntityManagers for different datasources. Also each entity mapping should be marked to been used only with one entity manager.
See full solution here:
http://www.baeldung.com/spring-data-jpa-multiple-databases
I am using JPA in my application, and it works once I query for objects, however it throw error javax.persistence.TransactionRequiredException: No transactional EntityManager available once I tried to save or update an object.
This is the java configuration:
#Configuration
#EnableTransactionManagement(proxyTargetClass = true)
#PropertySource("classpath:dao.properties")
public class JpaConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
.....................
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", ...........)
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setJpaProperties(jpaProperties);
entityManagerFactoryBean.setPackagesToScan("com....");
return entityManagerFactoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
Note I use proxyTargetClass = true in the #EnableTransactionManagement, since I do not want to create the useless interfaces in my application.
And this is the concrete implemention of the dao:
#Transactional
#Repository
public abstract class AbstractJPADao<I, E> {
#Autowired
#PersistenceContext
protected EntityManager entityManager;
private Class<E> type;
public AbstractJPADao() {
type=....
}
#Override
public Result<E> find(I id) {
E e = entityManager.find(type, id);
return Result.newInstance().setContent(e);
}
#Override
public Result<E> find(Map<String, Object> condition) {
Query q = entityManager.createQuery(".......));
return Result.newInstance().setContent(q.getResultList());
}
#Override
public E save(E element) {
entityManager.persist(element);
return element;
}
#Override
public E update(E element) {
entityManager.merge(element);
return element;
}
#Override
public void delete(E element) {
entityManager.remove(element);
}
}
#Repository
#Transactional
public class DepartmentDao extends AbstractJPADao<String, Department> {
#Override
protected String selectCause(Map<String, Object> condition) {
return "";
}
}
And the controller as the client of the dao:
#Controller
#RequestMapping("/api/deps")
public class DepartmentCtrl {
#Autowired
private DepartmentDao departmentDao;
#RequestMapping(value = "", method = RequestMethod.POST)
public Result create(#Valid Department department, BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
departmentDao.save(department);
return Result.newInstance().setContent(department);
}
throw new RuntimeException("...");
}
}
Is there anything wrong?
dao.properties:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/proj
jdbc.username=root
jdbc.password=
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
#hibernate.ejb.naming_strategy=true
hibernate.show_sql=true
hibernate.format_sql=true
Try renaming method transactionManager to txManager in the class JpaConfig
Autowiring goes by the name txManager
Edit
Also the framework could be expecting a no argument method for txManager. Can you try changing to
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
As noticed Tiny, you have two annotations #Autowired and #PersistenceContext over the protected field of type EntityManager in AbstractJPADao.
Try removing #Autowired. #PersistenceContext is enough to inject the EntityManager.
I'm using spring-jpa. I have 2 tests.
#Test
#Transactional
public void testFindAll() {
List<Engine> eList = engineService.findAll();
Engine e = eList.get(0); //this engine id=3
List<Translation> tList = e.getTranslations();
for(Translation t : tList) {
...
}
}
This method fails with this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize
a collection of role: xxx.Engine.translations, could not initialize
proxy - no Session
However, this method works just fine:
#Test
#Transactional
public void testFindOne() {
Engine e = engineService.findOne(3);
List<Translation> tList = e.getTranslations();
for(Translation t : tList) {
...
}
}
Why translation list is successfully loaded in one case, but not in another?
EDIT: service/repo code:
public interface EngineRepository extends JpaRepository<Engine, Integer>
{
}
.
#Service
#Transactional
public class EngineService
{
#Autowired
private EngineRepository engineRepository;
public List<Engine> findAll()
{
return engineRepository.findAll();
}
public Engine findOne(Integer engId)
{
return engineRepository.findOne(engId);
}
}
.
public class Engine implements Serializable {
...
#OneToMany
#JoinColumn(name="ID", referencedColumnName="TRAN_ID", insertable=false, updatable=false, nullable=true)
#LazyCollection(LazyCollectionOption.EXTRA)
private List<Translation> translations;
...
}
Config:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"xxx.dao"})
#ComponentScan(basePackages = {"xxx.dao", "xxx.service", "xxx.bean"})
#PropertySource("classpath:application.properties")
public class SpringDataConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(environment.getProperty("db.url"));
dataSource.setDriverClassName(environment.getProperty("db.driverClass"));
dataSource.setUsername(environment.getProperty("db.username"));
dataSource.setPassword(environment.getProperty("db.password"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("hibernate.showSQL"));
properties.put("hibernate.format_sql", environment.getProperty("hibernate.formatSQL"));
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("xxx.model");
entityManagerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I think the problem here is that the session gets closed after the first line in the first case. You should check out the JpaRepository implementation of findAll().
Integration Testing with Spring
It seems you're failing to provide a Spring Context within your TestCase, what that means? The #Transactional is being ignored. Therefore you end up with the closed session exception, because there is no transaction.
Take a look how to configure a TestCase with a Spring Context here
#RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
#ContextConfiguration(classes = {AppConfig.class, TestConfig.class})
public class MyTest {
#Autowired
EngineService engineService;
#Test
#Transactional
public void testFindOne() {}
#Test
#Transactional
public void testFindAll() {}
}
I am getting the error as in the question. My Dao Implement Class is as follows :
package com.argus.intenew;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
#Autowired
AnnotationSessionFactoryBean sessionFactory;
public UserDaoImpl() {
}
public AnnotationSessionFactoryBean getCurrentSessionFactory() {
return sessionFactory;
}
public void setCurrentSessionFactory(AnnotationSessionFactoryBean sessionfactory) {
this.sessionFactory = sessionfactory;
}
#Override
public void addUser(UserMap userMap) {
System.out.println("33333333333333333333");
getHibernateTemplate().save(userMap);
}
#Override
public List<User> findAllUser() {
return getHibernateTemplate().find("from User");
}
#Override
public void deleteUser(UserMap user) {
getHibernateTemplate().delete(user);
}
#Override
public void updateUser(UserMap user) {
getHibernateTemplate().update(user);
}
}
And my configuration class is as follows:
package com.argus.intenew;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "org.hibernate.dialect.MySQLDialect ";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "true";
#Bean
public DataSource dataSource() {
System.out.println("----------InDATAsource------------");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyUser");
dataSource.setUsername("root");
dataSource.setPassword("XXX");
System.out.println("----------OutofDATAsource------------");
return dataSource;
}
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
System.out.println("----------InsessionFactory------------");
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
String[] pckage={"com.argus.intenew"};
sessionFactory.setPackagesToScan(pckage);
sessionFactory.setHibernateProperties(hibProperties());
System.out.println("----------Outof session------------");
return sessionFactory;
}
private Properties hibProperties() {
System.out.println("----------InhipProp------------");
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.MySQLDialect ");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "true");
System.out.println("----------outofhip------------");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory().getObject());
return transactionManager;
}
#Bean
public UserBoImpl userBo() {
System.out.println("----------InUserBo------------");
UserBoImpl userBo= new UserBoImpl();
userBo.setUserDao(userDao());
System.out.println("----------OutofUserbo------------");
return userBo;
}
#Bean
public UserDaoImpl userDao() {
System.out.println("----------InUserDao------------");
UserDaoImpl userDao=new UserDaoImpl();
userDao.setCurrentSessionFactory(sessionFactory());
System.out.println("----------OutofUserDao------------");
return userDao;
}
}
Anyone please help and tell me what is the correct way to do this with annotations.
Here I am not using any xml file.
Your DAO implementation is not leveraging its superclass correctly.
You're injecting a Spring FactoryBean<SessionFactory> when it really needs a Hibernate SessionFactory.
It's not actually using the injected dependency.
You're attempting to use HibernateDaoSupport#getHibernateTemplate() without giving it a reference to a SessionFactory or a HibernateTemplate.
Note that HibernateDaoSupport will create its own HibernateTemplate as long as you give it a SessionFactory.
I suggest you make the following changes:
Remove AnnotationSessionFactoryBean sessionFactory from UserDaoImpl
Fix configuration of UserDaoImpl by leveraging its inherited setSessionFactory(SessionFactory) method
So you actually end up with this DAO code:
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
#Override
public void addUser(UserMap userMap) {
getHibernateTemplate().save(userMap);
}
#Override
public List<User> findAllUser() {
return getHibernateTemplate().find("from User");
}
#Override
public void deleteUser(UserMap user) {
getHibernateTemplate().delete(user);
}
#Override
public void updateUser(UserMap user) {
getHibernateTemplate().update(user);
}
}
And this configuration code:
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
//snip...
#Bean
public UserDaoImpl userDao() {
UserDaoImpl userDao=new UserDaoImpl();
userDao.setSessionFactory(sessionFactory().getObject());
return userDao;
}
}
Note that it's ok to return the FactoryBean from the sessionFactory() configuration method since Spring will detect and utilize its lifecycle methods (via InitializingBean and DisposableBean), but you need to accommodate by calling the FactoryBean method getObject() yourself.
Don't user HibernateDaoSupport and/or HibernateTemplate. With the release of Hibernate 3.0.1 that support should be regarded deprecated. As mentioned in the reference guide implement the dao/repository based on plain hibernate.
Your dao will look like
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(UserMap userMap) {
System.out.println("33333333333333333333");
sessionFactory.getCurrentSession().save(userMap);
}
#Override
public List<User> findAllUser() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
#Override
public void deleteUser(UserMap user) {
sessionFactory.getCurrentSession().delete(user);
}
#Override
public void updateUser(UserMap user) {
sessionFactory.getCurrentSession().update(user);
}
}
As you are already using the #ComponentScan annotation (and I assume yo have your BO annotated with #Service and properly annotated with #Autowired there is no need to explictly configure you dao and service in the configuration.
#Configuration
#ComponentScan(basePackages = {"com.argus.intenew"})
public class Webconfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "org.hibernate.dialect.MySQLDialect ";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "true";
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/MyUser");
dataSource.setUsername("root");
dataSource.setPassword("XXX");
return dataSource;
}
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
String[] pckage={"com.argus.intenew"};
sessionFactory.setPackagesToScan(pckage);
sessionFactory.setHibernateProperties(hibProperties());
return sessionFactory;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, "org.hibernate.dialect.MySQLDialect ");
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, "true");
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager(sessionFactory().getObject());
}
}
A note regarding DriverManagerDataSource this is nice for testing but please don't use this in production (unless you want an application that doesn't perform). Use a proper JDBC Connection Pool instead.
A final note, if you really want productivity drop hibernate, switch to JPA and use Spring Data JPA for your repositories. Saves you writing a lot of implementation code. (And the best maintainable and testable code is code not written :) ).