如何在Java类中使用@Bean配置数据源

时间:2018-08-29 10:31:31

标签: java hibernate spring-mvc datasource javabeans

我正在按照Spring书中的示例创建一个小的网络商店应用程序。

该示例使用 hsqldb 嵌入式数据库,但我不想使用它。

我想连接到 MySQL 数据库,然后使用 Hibernate sessionFractory

我以这种方式编辑了示例代码:

@Configuration
@ComponentScan("com.packagename.webstore")
public class RootApplicationContextConfig {

    @Bean 
    public DataSource dataSource() { 
       // this is the original code of the example
      /*EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); 
        EmbeddedDatabase db = builder 
                .setType(EmbeddedDatabaseType.HSQL) 
                .addScript("db/sql/create-table.sql") 
                .addScript("db/sql/insert-data.sql") 
                .build(); 
        return db; */

          //this is my code
          DriverManagerDataSource dataSource = new DriverManagerDataSource();
          dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql://localhost:3306/dbName");
          dataSource.setUsername( "user" );
          dataSource.setPassword( "pass" );
          return dataSource;
    } 

}

然后,在我的班级中,我以这种方式访问​​数据源:

@Autowired
private DataSource datasource;    
...
Connection connection  = datasource.getConnection();
...

我做的对吗?

如果以后要使用Hibernate sessionFactory,应该如何编辑代码?

谢谢你们

1 个答案:

答案 0 :(得分:0)

如果要使用spring配置SessionFactory,则可以像下面那样创建所需的bean

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "org.baeldung.spring.persistence" })
public class PersistenceConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(
        new String[] { "entity class package name so it can scan them" });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      BasicDataSource dataSource = new BasicDataSource();
      dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
      dataSource.setUrl(env.getProperty("jdbc.url"));
      dataSource.setUsername(env.getProperty("jdbc.user"));
      dataSource.setPassword(env.getProperty("jdbc.pass"));

      return dataSource;
   }

   @Bean
   @Autowired
   public HibernateTransactionManager transactionManager(
     SessionFactory sessionFactory) {

      HibernateTransactionManager txManager
       = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory);

      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         {
            setProperty("hibernate.hbm2ddl.auto",
              env.getProperty("hibernate.hbm2ddl.auto"));
            setProperty("hibernate.dialect",
              env.getProperty("hibernate.dialect"));
            setProperty("hibernate.globally_quoted_identifiers",
             "true");
         }
      };
   }
}

属性文件

# jdbc confi
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql

# hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

然后您就可以在所需的类中访问Datasource或SessionFactory

public  class HibernateDAO{

   @Autowired
   SessionFactory sessionFactory;

@Autowired
   DataSource datasource;
 }

以下是示例link