Spring整合hibernate-用代码配置代码Appconfig.class

使用代码配置代码:具体如下
Spring整合hibernate基本配置:

package org.mobiletrain.aopspring;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.mobiletrain.aopspring.biz.UserService;
import org.mobiletrain.aopspring.biz.impl.UserServiceImpl;
import org.mobiletrain.aopspring.dao.UserDao;
import org.mobiletrain.aopspring.dao.impl.UserDaoDbImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class Appconfig {
    
    @Bean
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        return new HibernateTransactionManager(sessionFactory);
    }
    
    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/hib?useUnicode=true&character=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
    
    @Bean
    public LocalSessionFactoryBean SessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPackagesToScan(new String[] {"org.mobiletrain.aopspring.entity"}); 
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        props.setProperty("hibernate.show_sql", "true");
        props.setProperty("hibernate.format_sql", "true");
        bean.setHibernateProperties(props);
        return bean;
    }
    
    @Bean
    public UserService userService() {
        return new UserServiceImpl();
    }
    
    @Bean
    public UserDao userDao() {
        return new UserDaoDbImpl();
    }
}

你可能感兴趣的:(Spring整合hibernate-用代码配置代码Appconfig.class)