Hibernate one-to-one mapping association

Source: Internet
Author: User

Hibernate provides two ways to map relationships on a one-to-one basis:

1) Follow foreign key mapping

2) Follow the primary key mapping

The following is an example of the Employee Account form and the Employee Profile table (a one-to-two relationship between the employee account and the file table), which is described in the following two mapping relationships, and each of these mappings is used to perform persistent operations

(1) The employee file is saved and assigned to an employee account.

(2) Load the account information while loading the employee profile

One: Map by foreign key

Hibernateutil Tool Class (for getting session and closing session)

Package Cn.util;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernateutil {//Initializes a Threadlocal object with get and set methods private static final Th        Readlocal<session> sessiontl=new threadlocal<session> ();        private static configuration configuration;    Private final static sessionfactory sessionfactory;        static{configuration=new Configuration (). Configure ();    Sessionfactory=configuration.buildsessionfactory (); }//Get Session object public static session Currentsession () {//sessiontl's Get method returns its corresponding thread-internal variable based on the current thread, that is, the session object, the multithreading case        The next shared database connection is not secure.        Threadlocal guarantees that each thread has its own session object session session= (session) Sessiontl.get ();            if (session==null) {session=sessionfactory.opensession ();        Sessiontl.set (session);    } return session; }//Close Session object public static void CloseSession () {session session= (session) SESSiontl.get ();        Sessiontl.set (NULL);    Session.close (); }}

Create entity Classes Users1 and Resume1

Users1:

Package cn.entity_fk;/** * Employee Class * * *  */public class Users1 {    private Integer userid;//user number    private String username;//name    private string userpass;//password    private Resume1 resume1;//Archive object public        Users1 () {    } Public        Users1 (string username, string userpass) {            this.username = Username;        This.userpass = Userpass;            }    Public Integer GetUserid () {        return userid;    }    public void Setuserid (Integer userid) {        this.userid = userid;    }    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String Getuserpass () {        return userpass;    }    public void Setuserpass (String userpass) {        this.userpass = userpass;    }    Public Resume1 getResume1 () {        return resume1;    }    public void setResume1 (Resume1 resume1) {        this.resume1 = resume1;    }}

RESUME1:

 Package cn.entity_fk;/** * Archive class * * @time * @author Happy * */public class Resume1 {private Integer resid;//File compilation Number private String resname;  File name Private String rescardno;//number private Users1 users1; The subordinate user (employee) public Resume1 () {} public Resume1 (string resname, String rescardno) {this.        Resname = Resname;            This.rescardno = Rescardno;    } public Integer Getresid () {return resid;    } public void Setresid (Integer resid) {this.resid = Resid;    } public String Getresname () {return resname;    } public void Setresname (String resname) {this.resname = Resname;    } public String Getrescardno () {return rescardno;    } public void Setrescardno (String rescardno) {this.rescardno = Rescardno;    } public Users1 getUsers1 () {return users1;    } public void SetUsers1 (Users1 users1) {this.users1 = users1; }}

Create configuration Files Users1.hbm.xml and Resume1.hbm.xml

Users1.hbm.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">

Resume1.hbm.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">

Hibernate.cfg.xml Large configuration file:

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibern Ate.org/dtd/hibernate-configuration-3.0.dtd ">

Test class:

/** * One-to-one     correlation test     */public class Tests {    session session;    Transaction TX;        @Before public    void Initdate () {        session = Hibernateutil.getsession ();         tx= session.begintransaction ();    }            @After public     void Aftertest () {         tx.commit ();         Hibernateutil.closesession ();     }            /** * One-to-one     correlation test */     @Test public    void Gettest () {        Users1 u1=new Users1 ();        U1.setusername ("Fire");        U1.setuserpass ("2");                Resume1 r1=new Resume1 ();        R1.setresname ("Training 2");        R1.setrescardno ("002");                U1.SETRESUME1 (R1);        R1.setusers1 (U1);        Session.save (R1);        System.out.println ("OK-------");    }        /**     * Query */    @Test public    void Selecttest () {         Users1 u1= (Users1) session.load (Users1.class, 2 );          System.out.println (U1.getresume1 (). Getresname ());            }

Results:

Database:

Database:

Users1 table:

RESUME1 table:

Second: Follow the primary key mapping

The UserID field of the Users2 table is the primary key, and as a foreign key reference the primary key of the Resume2 table, which is the Users2 table and the Resume2 table share primary key (the primary key value in Users2 is based on the value of the Resume2-generated primary key value)

Resume2:

Package cn.entity_pk;/** * Archive class *  * @time * @author Happy *  */public class Resume2 {    private Integer resid;
   
    private String Resname;    Private String Rescardno;    Private Users2 users2;        Public Users2 getUsers2 () {        return users2;    }    public void SetUsers2 (Users2 users2) {        this.users2 = users2;    }    Public Resume2 () {    } public        Resume2 (string resname, String rescardno) {                this.resname = resname;        This.rescardno = Rescardno;            }    Public Integer Getresid () {        return resid;    }    public void Setresid (Integer resid) {        this.resid = resid;    }    Public String Getresname () {        return resname;    }    public void Setresname (String resname) {        this.resname = resname;    }    Public String Getrescardno () {        return rescardno;    }    public void Setrescardno (String rescardno) {        this.rescardno = Rescardno;    }    }
   

USERS2:

Package cn.entity_pk;/** * Employee class *  * @author Happy *  */public class Users2 {    private Integer userid;    Private String username;    Private String Userpass;    Private Resume2 resume2;        Public Resume2 getResume2 () {        return resume2;    }    public void SetResume2 (Resume2 resume2) {        this.resume2 = resume2;    }    Public Users2 () {    } public        Users2 (string username, string userpass) {            this.username = Username;        This.userpass = Userpass;            }    Public Integer GetUserid () {        return userid;    }    public void Setuserid (Integer userid) {        this.userid = userid;    }    Public String GetUserName () {        return username;    }    public void Setusername (String username) {        this.username = username;    }    Public String Getuserpass () {        return userpass;    }    public void Setuserpass (String userpass) {        this.userpass = userpass;    }    }

Resume2.hbm.xml Mapping File:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en"                            "http://www.hibernate.org/dtd/ Hibernate-mapping-3.0.dtd ">

Users2.hbm.xml Mapping File:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-mapping public     "-//hibernate/hibernate mapping DTD 3.0//en"    "Http://www.hibernate.org/dtd /hibernate-mapping-3.0.dtd ">

Test class:

public class TEST_PK {    session session;    Transaction TX;        @Before public    void Initdate () {        session = Hibernateutil.getsession ();         tx= session.begintransaction ();    }            @After public     void Aftertest () {         tx.commit ();         Hibernateutil.closesession ();     }            /** * One-to-one     correlation test: Follow the primary key mapping     */@Test public    void Gettest () {        Users2 u1=new Users2 ();        U1.setusername ("hehe");        U1.setuserpass ("1");                Resume2 r1=new Resume2 ();        R1.setresname ("haha");        R1.setrescardno ("001");                U1.setresume2 (R1);        R1.setusers2 (U1);        Session.save (R1);        System.out.println ("OK-------");            }        /**     * Query */    @Test public    void Selecttest () {        Users2 u1= (Users2) session.load (Users2.class, 2 );        System.out.println (U1.getresume2 (). Getresname ());            }

Results:

Database:

Resume2 table:

USERS2 table:

Hibernate one-to-one mapping association

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.