Hibernate configuration file,

Source: Internet
Author: User

Hibernate configuration file,

 

Hibernate configuration file Overview:

Configuration files related to Hibernate include hibernate. cfg. xml, hibernate. properties, xxx. hbm. xml (Object Class ing file), etc. Hibernate: http://hibernate.org/orm/

Directory: hibernate configuration file

1. Reading sequence of hibernate configuration files

The hibernate configuration file can be configured in two ways: the XML configuration file and the property configuration file officially recommended. Most of us adopt XML configuration, because the structure is good, the configuration is flexible, and the readability is strong. In addition, you can directly configure the ing file in XML, but not the property file. However, we may ignore the following problem: the configuration file that hibernate first looks for is the property configuration file hibernate. properties.
Take a look at the figure below.
 
We can see that Hibernate first went to the hibernate. properties configuration file, but not found. Then create the bytecode support, use cglib, and then use the timestamp control, and then read the hibernate. cfg. xml configuration file. We may ignore the preceding log information, but we need to understand some Loading Principles of hibernate. Since Hibernate reads the attribute configuration file first, we will use the attribute configuration file as an example to see the effect.
 
Compress the XML file into a. bak file and add it to the property configuration file. The configuration is the same as that in XML.

hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver  hibernate.connection.url=jdbc:oracle:thin:@localhost:1521:orcl  hibernate.connection.username=hibernate  hibernate.connection.password=hibernate  hibernate.dialect=org.hibernate.dialect.OracleDialect  hibernate.current_session_context_class=thread  hibernate.show_sql=true  hibernate.format_sql=true  

 

In the program, we can write it in this way.

Package demo; import java. util. date; import org. hibernate. *; import org. hibernate. cfg. configuration; import demo. domain. user; public class Test {public static void main (String [] args) {Configuration config = new Configuration (); config. addResource ("demo/domain/User. hbm. xml "); // load the ing file // config. addClass (demo. domain. user. class); another loading method is SessionFactory sessionFactory = config. buildSessionFactory (); Session session = sessionFactory. getCurrentSession (); Transaction tx = session. beginTransaction (); User user = new User (); user. setName ("Sarin"); user. setPhone ("15912345678"); user. setDepartment ("R & D department"); user. setCity ("Dalian"); user. setHireTime (new Date (); session. save (user); tx. commit ();}}

 

On the console, we can see such log information.
 
It can be seen that Hibernate directly reads the configuration information, and then provides bytecode support, initializes the timestamp, loads the ing file, and the subsequent process is the same.
Hibernate. properties and hibernate. cfg. xml is the default naming method used by Hibernate to parse the configuration file, and must be placed in the root directory of the class path. Of course, it is not recommended to modify it during use, because this is the case. If you do not like this naming method, you can customize the name. However, you must tell the Hibernate configuration file which is used in this case. It is convenient to do so as follows.

File file = new File("src/demo/hibernate.xml");  Configuration config = new Configuration();  config.configure(file);  

 

At the same time, Hibernate supports setting new attributes in the program. For example, if we do not set the show_ SQL and format_ SQL attributes during configuration, we can also set them in the program as follows.

config.setProperty(Environment.SHOW_SQL, "true");  config.setProperty(Environment.FORMAT_SQL, "true");  

All the configurable attributes in Hibernate are static member variables in the org. hibernate. cfg. Environment class. In this way, new attributes are added to the program.
The org. hibernate. cfg. Configuration class resolves Configuration information and ing information, and then creates a SessionFactory object. At this time, the Configuration information is bound to SessionFactory, so Configuration is useless. This part of the Hibernate source code is also better understood.

 

2. hibernate. properties

hibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialecthibernate.dialect=org.hibernate.dialect.MySQLMyISAMDialecthibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost:3306/jdbchibernate.connection.username=roothibernate.connection.password=123123

Note: In the project/etc directory of the Hibernate core software package, there is a hibernate. properties file, which provides configuration code samples for connecting to various relational databases.

3. hibernate. cfg. xml

<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">Xxx. hbm. xml (Object Class ing file)
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

 

Note: After hibernate is downloaded and decompressed, it is easy to find a sample of the configuration file and ing file in the decompressed folder. jar racks are well classified.

Read configuration files

1. Load the configuration from hibernate. cfg. xml. The object ing file is in xml format.

import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil {        private static SessionFactory sessionFactory;        static{        try{            Configuration config = new Configuration().configure();            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());            setSessionFactory(config.buildSessionFactory(builder.build()));        }catch(Exception e){            e.printStackTrace();        }    }            public static void shutdown(){        getSessionFactory().close();    }    public static SessionFactory getSessionFactory() {        return sessionFactory;    }    public static void setSessionFactory(SessionFactory sessionFactory) {        HibernateUtil.sessionFactory = sessionFactory;    }}

 

2. Load the configuration from hibernate. cfg. xml, load the @ annotation object class, and load the configuration file

Import org. hibernate. SessionFactory; import org. hibernate. cfg. AnnotationConfiguration;/* Hibernate tool class officially provided by Hibernate. The main function is to return a Session. The * @ AnnotationConfiguration class is required for loading the object class of @ annotation configuration. The HibernateUtil class contains a SessionFactory object. * Hibernate. cfg. xml is loaded during class initialization and SessionFactory is initialized. You can use SessionFactory to open Session and operate entity classes. */Public class HibernateUtil {private static final SessionFactory sessionFactory; // The static {// static code block of the SessionFactory object in single-State mode. When the class is loaded, the Hibernate try {// from hibernate. cfg. load the configuration in xml, load the @ annotation object class, and load the configuration file sessionFactory = new AnnotationConfiguration (). configure ("hibernate. cfg. xml "). buildSessionFactory ();} catch (Throwable ex) {System. err. println ("Initial SessionFactory creation failed. "+ ex); throw new ExceptionInInitializerError (ex);} public static SessionFactory getSessionFactory () {// static method, return SessionFactory return sessionFactory ;}}

 

Resolution:

The Configuration class is used to manage the information of our configuration files. Through it, we can create a configuration instance to manage the corresponding Configuration documents, but usually we only create one configuration instance.

Here, we can see that to create a Configuration, you can use

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

 

Here, we need to understand that Configuration is the portal through which to obtain the Configuration file.

Configuration can also be passed by specifying parameters:
See the following:

File file = new File("c:\\Hibernate.xml"); Configuration config = new Configuration().config(file); 

 

Configuration also has some important methods:

addProperties(); setProperties(); 

 

The following is an example:

Properties properties = Porperties.load("a.properties"); Configuration configure = new Configuration().setProperties(properties); 

 

You can also specify the. hbm. xml file. Below are several methods:

addClass(); addFile(); addURL(); 

 

The following is an example:

Configuration configure = new Configuration().addClass(Order.class); Configuration configure = new Configuration().addURL(Configuration.class.getResource(Order.hbm.xml)); Configuration configure = new Configuration().addFile("Order.hbm.xml"); 

 

Let's take a brief look at the SessionFactory class.
First, let's take a look at the code.

Configuration configure = new Configuration().configure(); SessionFactory sessions = configure.buildSessionFactory(); 

 

It should be noted that SessionFactory is thread-safe and can be called by multiple threads. In our actual development, we can construct a SessionFactory in the initialization part, for example, initializing a readonly constant of SessionFactory in a public static class. It acts as the data storage source proxy. The factory model is used here. Note that SessionFactory is not lightweight, because generally, only one SessionFactory is required for a project. When you need to operate multiple databases, you can specify a SessionFactory for each database.

Reference: http://www.cnblogs.com/xiohao/p/4150293.html
Http://www.cnblogs.com/black-snail/p/3767548.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.