直接设置Property
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource
import org.hibernate.SessionFactory
import org.hibernate.cfg.Environment
@Configuration
@PropertySource("classpath:jdbc.properties")
open class JavaConfig {
@Bean
open fun getSessionFactory(basicDataSource: BasicDataSource): SessionFactory {
return org.hibernate.cfg.Configuration().let { configuration ->
// The property: "hibernate.connection.*"
configuration.setProperty(Environment.DRIVER, basicDataSource.driverClassName)
configuration.setProperty(Environment.USER, basicDataSource.username)
configuration.setProperty(Environment.PASS, basicDataSource.password)
configuration.setProperty(Environment.URL, basicDataSource.url)
return@let try {
configuration.buildSessionFactory()
} catch (err: Throwable) {
println("Can't connect to DataBase!")
throw err
}
}
}
// Without DBCP, just using field name of BasicDataSource class.
@Bean
open fun getDataSource(@Value("${password:123456}") _passwd: String,
@Value("${url:jdbc:mysql://127.0.0.1:3306/db}") _url: String): BasicDataSource {
println(_url)
return BasicDataSource().apply {
driverClassName = "com.mysql.cj.jdbc.Driver"
username = "root"
password = _passwd
url = _url
}
}
}
DBCP数据库连接池
@Configuration
@PropertySource("classpath:jdbc.properties")
open class JavaConfig {
@Bean
open fun getSessionFactory(basicDataSource: DataSource): SessionFactory {
return org.hibernate.cfg.Configuration().let { configuration ->
return@let try {
configuration.buildSessionFactory(
StandardServiceRegistryBuilder().apply {
// applySettings(configuration.properties)
applySetting(Environment.DATASOURCE, basicDataSource)
}.build()
)
} catch (err: Throwable) {
println("Can't connect to DataBase!")
throw err
}
}
}
// With DBCP
@Bean
open fun getDataSource(@Value("${password:123456}") _passwd: String,
@Value("${url:jdbc:mysql://127.0.0.1:3306/db}") _url: String): BasicDataSource {
println(_url)
return BasicDataSource().apply {
driverClassName = "com.mysql.cj.jdbc.Driver"
username = "root"
password = _passwd
url = _url
}
}
}
@See: https://www.boraji.com/hibernate-5-commons-dbcp-connection-pooling-example
@See: https://stackoverflow.com/questions/4406935/how-can-i-set-datasource-when-im-creating-hibernate-sessionfactory