Hibernate Getting Started 03 - Profile

xiaoxiao2021-03-06  39

Getting Started 03 - Profile

Hibernate can use the XML or property file to configure sessionFactory, the preset profile name is hibernate.cfg.xml or hibernate.properties. The example of using an XML file in the previous topic is as follows:

Hibernate.cfg.xml

>

PUBLIC "- // Hibernate / Hibernate Configuration DTD // EN"

"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

True

Net.sf.hibernate.dialect.mysqldiaAlaforct

com.mysql.jdbc.driver

JDBC: mysql: // localhost / hibernatetest

Caterpillar

123456

When configuring the XML file, you can specify the image file location of the object and the database table, the location of the XML configuration file must be in the ClassPath setting, such as the location of the main program, or web-inferi In / Classes, we use the following way to read the XML file to configure Hibernate:

SESSIONFACTORY SF = New Configuration (). Configure (). BuildSessionFactory ();

Configuration represents a collection of Java objects and database table images and is used to establish sessionFactory, then Configuration no longer works. The preset XML file name is hibernate.cfg.xml, you can also specify the name of the file, for example: sessionFactory sf = new configuration ()

.configure ("db.cfg.xml")

.BUILDSessionFactory ();

In addition to configuring the XML file, we can also configure the attribute file, the file name is hibernate.properties, an example below:

Hibernate.properties

Hibernate.show_sql = TRUE

Hibernate.diaforct = net.sf.hibernate.dialect.mysqldiaLect

Hibernate.Connection.driver_class = com.mysql.jdbc.driver

Hibernate.Connection.url = jdbc: mysql: // localhost / hibernatetest

Hibernate.Connection.userName = Caterpillar

Hibernate.connection.password = 123456

Hibernate.properties must be in the set of ClassPath, such as the location of the main program, or the web-inf / class of the web program, and the image file of the Web program, we must be in the program. The following is loaded as follows:

Configuration CFG = New Configuration ()

.addclass (onlyfun.caterpillar.user.class)

.addclass (onlyfun.caterpillar.Item.class);

In this way, the program will automatically load online / caterpillar / user.hbm.xml and online / caterpillar / item.hbm.xml, after the Hibernate configuration is completed, we can get SessionFactory:

SESSIONFACTORY sessions = cfg.buildsessionFactory ();

For more details on Hibernate configuration, you can view the Hibernate reference manual.

转载请注明原文地址:https://www.9cbs.com/read-68529.html

New Post(0)