【发布时间】:2019-02-04 02:46:12
【问题描述】:
我正在按照 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,我应该如何编辑我的代码?
谢谢大家
【问题讨论】:
-
如果有什么特别的理由不把这些值放在你的
application.properties中并让 Boot 处理它?
标签: java hibernate spring-mvc datasource javabeans