Getting started with Hibernate framework Association ing and hibernate framework ing

Source: Internet
Author: User

Getting started with Hibernate framework Association ing and hibernate framework ing

Ing is to map the ing relationship to the database, which is one or more references in the object model.

1. Configure one-way multi-to-one Association

Define a Dept attribute in the Emp class, but do not need to define the set attribute used to store the Emp object in the Dept class.

01. Dept. java

Package cn. zhang. entity; // Department entity class public class Dept {private Integer deptid; // No. private String deptname; // name public Integer getDeptid () {return deptid ;} public void setDeptid (Integer deptid) {this. deptid = deptid;} public String getDeptname () {return deptname;} public void setDeptname (String deptname) {this. deptname = deptname ;}}

02. Emp. java

Package cn. zhang. entity; // employee entity class public class Emp {private Integer empno; // number private String empname; // name private Dept dept; // Department public Dept getDept () {return dept;} public void setDept (Dept dept) {this. dept = dept;} public Integer getEmpno () {return empno;} public void setEmpno (Integer empno) {this. empno = empno;} public String getEmpname () {return empname;} public void setEmpname (String empname) {this. empname = empname ;}}

03. Dept. hbm. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

04. Emp. hbm. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

05. hibernate. cfg. xml configuration file

<? Xml version = '1. 0' encoding = 'utf-8'?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN "" http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd "> <Hibernate-configuration> <session-factory> <! -- Database connection settings --> <property name = "connection. driver_class "> oracle. jdbc. oracleDriver </property> <property name = "connection. url "> jdbc: oracle: thin: @ localhost: 1521: orcl </property> <property name =" connection. username "> zhangzong </property> <property name =" connection. password "> 123 </property> <! -- SQL dialect (SQL dialect) --> <property name = "dialect"> org. hibernate. dialect. Oracle10gDialect </property> <! -- Drop and re-create the database schema on startup --> <property name = "hbm2ddl. auto"> create </property> <! -- Echo all executed SQL to stdout: print the background SQL statement on the console --> <property name = "show_ SQL"> true </property> <! -- Format and display SQL --> <property name = "format_ SQL"> true </property> <! -- JDBC connection pool (use the built-in) --> <! -- <Property name = "connection. pool_size"> 1 </property> --> <! -- Enable Hibernate's automatic session context management specifies the current session range and context --> <! -- <Property name = "current_session_context_class"> thread </property> --> <! -- Disable the second-level cache --> <! -- <Property name = "cache. provider_class "> org. hibernate. cache. noCacheProvider </property> --> <mapping resource = "cn/zhang/entity/Dept. hbm. xml "/> <mapping resource =" cn/zhang/entity/Emp. hbm. xml "/> </session-factory> 

06. The tool class HibernateUtil for obtaining session objects and Closing session objects

Package cn. zhang. util; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. cfg. configuration; public class HibernateUtil {// initialize a ThreadLocal object with the get and set Methods private static final ThreadLocal <Session> sessionTL = new ThreadLocal <Session> (); private static Configuration configuration Configuration; private final static SessionFactory sessionFactory; static {configuration = new Configuratio N (). configure (); sessionFactory = configuration. buildSessionFactory ();} // get the session object public static Session currentSession () {// The get method of sessionTL returns the corresponding internal thread variable, that is, the Session object, based on the current thread, multi-threaded shared database connections are insecure. // ThreadLocal ensures that each thread has its own session object Session = (session) sessionTL. get (); if (session = null) {session = sessionFactory. openSession (); sessionTL. set (session) ;}return session ;}// close the session object public static void closeSession () {Session session Session = (session) sessionTL. get (); sessionTL. set (null); session. close ();}}

07. Test class

@ Test // one-to-one public void TestOne () {Session session = HibernateUtil. currentSession (); Transaction tx = session. beginTransaction (); Dept dept = new Dept (); dept. setDeptname ("Development Department"); Emp emp = new Emp (); emp. setDept (dept); emp. setEmpname ("ZHANG Zong"); session. save (dept); session. save (emp); tx. commit (); HibernateUtil. closeSession ();}
2. Configure two-way one-to-Multiple Association

In the previous example, we have established a one-to-one association between the Emp class and the Dept class. Next we will add a one-to-Multiple Association Between the Dept class and the Dept class,

Add an emps attribute of the set type to the Dept class:

Private Set <Emp> emps = new HashSet <Emp> (); // public Set of employee sets <Emp> getEmps () {return emps ;} public void setEmps (Set <Emp> emps) {this. emps = emps ;}

In Dept. hbm. xml, it will also be changed:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 

Supplement: cascade attributes and inverse attributes (a new blog will be written)

01. "cascade" attributes

"Cascade"-the literal translation is "cascade, concatenate", which is interpreted as "this attribute will enable us to operate the main object, at the same time, Hibernate helps us complete the operations on the subordinate objects (for example, there are two tables, Customer and Order, with a one-to-many relationship. When we only use JDBC to delete a row of records in the Customer table, we also need to manually delete all the records associated with the Order table. After using the 'cascade 'attribute of Hibernate, when we delete a Customer record, hibernate will help us Delete the corresponding Order table records, which facilitates our work )".

02. "inverse" attributes

"Inverse"-the literal translation means "reverse, so that it is reversed, the implicit explanation is "whether to give the power of relationship maintenance to the other party" (This explanation is really cool -_-!!, Is not understandable ). The "inverse" attribute in Hibernate has only two values: "true" and "false ". "True" indicates that the power to maintain the relationship is handed over to the other party, and "false" indicates that the power to maintain the relationship is not handed over (default value ).

Recommended blog: http://www.cnblogs.com/o-andy-o/archive/2012/03/26/2418235.html

Test:

@ Test public void TestThree () {// obtain the session object Session = HibernateUtil. currentSession (); // enable Transaction tx = session. beginTransaction (); // create a Dept object and Emp object Dept dept = new Dept (); dept. setDeptname ("Employment Department"); Emp emp = new Emp (); emp. setEmpname ("Kun"); // establishes a one-to-many bidirectional association between Dept and Emp objects. setDept (dept); dept. getEmps (). add (emp); // Save the session of the Dept object. save (dept); // submit the transaction tx. commit (); // close session connection HibernateUtil. closeSession ();}

 

3. Configure one-way, multiple-to-Multiple Association (To be continued ...)

Related Article

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.