Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting properties programmatically in Hibernate

Tags:

hibernate

How can I ensure that all properties are loaded from hibernate.cfg.xml, then add additional properties programmatically? I saw the following code snippet but it looks like a completely new configuration, not an addition to an existing one.

Configuration c = new Configuration();
c.configure();

c.setProperty("hibernate.connection.username", "abc" );
c.setProperty("hibernate.connection.password", "defgh629154" ); 
like image 328
KyleM Avatar asked May 20 '11 16:05

KyleM


People also ask

How many ways we can configure database properties in Hibernate?

You can configure Hibernate mainly in three ways: Use the APIs (programmatically) to load the hbm file along with the database driver providing connection details. By specifying the database connection details in an XML configuration file that's loaded along with the hbm file. The default file name is hibernate.

What is Hibernate SessionFactory and how do you configure it?

Most importantly, the SessionFactory in Hibernate is responsible for the creation of Session objects. The Hibernate Session provides methods such as save, delete and update, all of which are used to perform CRUD-based operations on the database to which the SessionFactory connects.

How do I set Hibernate Dialect?

SQL Dialects in Hibernate The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements. For connecting any hibernate application with the database, it is required to provide the configuration of SQL dialect.


2 Answers

The code snippet you showed is what you need. Just use your existing configuration instead of creating a new one.

If it is not you who instantiates the configuration (but, for example, spring), you'd need to extend the class that creates it.

like image 193
Bozho Avatar answered Oct 27 '22 03:10

Bozho


You code snippet should load hibernate.cfg.xml from the root of the classpath and then add or overwrite the configuration properties programmatically . So , please make sure that your so called the "existing one hibernate.cfg.xml " is on the root of the classpath.

If your "existing one hibernate.cfg.xml " is not on root of the classpath , but in some package , you can load it by specifying its package path in the configure() , likes

Configuration config = new Configuration();
config.configure("package1/package2/hibernate.cfg.xml");
config.setProperty("hibernate.connection.username", "update" );
config.setProperty("hibernate.connection.password", "defgh629154" ); 
like image 21
Ken Chan Avatar answered Oct 27 '22 01:10

Ken Chan