Hibernate Access Multiple Databases
Author: Yang
Source: http://blog.sina.com.cn/u/1237288325
First, Hibernate is loaded when accessing the database
For most friends using Hibernate, usually use the way to get the Configuration instance: Configuration Configure = New Configuration (). Configure ();
In Hibernate, Configuration is the entrance to Hibernate. When instantification of a Configuration, Hibernate automatically looks for the Hibernate Profile Hibernate.properties in the Environment Variable (ClassPath). If this file exists, load the content of the file into a Properties Example Global_Properties, if not, you will print information hibernate.properties not found;
Next, Hibernate adds all system environment variables (System.getProperties ()) to global_properties. If the configuration file hibernate.properties exists, the system will further verify the validity of this file configuration. For some unsupported configuration parameters, the system will print a warning message.
By default, the configure () method automatically looks for the Hibernate.cfg.xml under the Environment Variable (ClassPath). If the file does not exist, the system will print the following information and throw HibernateException: hibernate.cfg.xml Not found If the file exists, the configure () method will first access
Next, the configure () method accesses the child elements of
Then Configure () will access the content of the following elements in turn.
Where
This configure () method creates a Configuration instance using various resources. For the entire project, if this Configuration instance is stored with a local thread, the entire project only needs to instantiate the Configuration object (Note: The Configuration instance takes time), which improves the efficiency of the project. Second, Hibernate Access Multiple Database Configuration
According to the above, the configure () method defaults to load us by accessing the Hibernate.cfg.xml
Configuration config = new configuration (). Addfile ("/ cat.hbm.xml);
This way, if multiple databases are configured with an XML configuration, then write multiple profiles. Here, assume that the corresponding two databases (one is mysql, one is SQLServer), we can define its XML file as "mysql.cfg.xml" and "sqlserver.cfg.xml". Configuration SessionFactory is acquired by the class code as follows: SessionFactory mysqlFactory = new Configuration () configure ( "/ mysql.cfg.xml") buildSessionFactory (); SessionFactory sqlserverFactory = new Configuration () configure ( "sqlserver.cfg.xml... ") .BUILDSESSIONFACTORY ();
If you use spring, multi-database is more simple, like this code can complete all configurations:
/ Bean>
Yang Xiao, Master of Computer, served as Java development in NEC and SoftBrain.
Blog: http://blog.sina.com.cn/u/1237288325