Allow-to-one
Assume two objects, respectively person and address.
One address contains multiple persons.
Create classes respectively
Package CN. itcase. hibernate. domain; Public Class Address { Private Int ID; Private String Street; Public Int GETID (){ Return ID ;} Public Void Setid ( Int ID ){ This . ID = ID ;} Public String getstreet (){ Return Street ;} Public Void Setstreet (string Street ){ This . Street = Street ;}} Package CN. itcase. hibernate. domain; Public Class Person { Private Int ID; Private String name; Private Address; Public Address getaddress (){ Return Address ;} Public Void Setaddress (Address ){ This . Address = Address ;} Public Int GETID (){ Return ID ;} Public Void Setid (Int ID ){ This . ID = ID ;} Public String getname (){ Return Name ;} Public Void Setname (string name ){ This . Name = Name ;}}
The corresponding configuration file is
<? XML version = "1.0"?> <! Doctype hibernate-mapping public "-// hibernate/hibernate DTD ing DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
// Test multiple-to-one example
Package CN. itcast. hibernate; import Java. util. hashset; import Java. util. set; import Org. hibernate. hibernate; import Org. hibernate. session; import Org. hibernate. transaction; import CN. itcase. hibernate. domain. address; import CN. itcase. hibernate. domain. person; public class many2one2 {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubperson depart = add (); person EMP = Qu Ery (1); // system. out. println (EMP. getdepart (). getname (); // querydepart (3); // system. out. println (addrquery (1 ). getper (). getname ();} static address addrquery (int id) {session S = NULL; transaction Tx = NULL; try {S = hibernateutil. getsession (); Tx = S. begintransaction (); Address ADDR = (Address) s. get (address. class, ID); // system. out. print (EMP. getdepart (). getname (); hibernate. initialize (ADDR. getstreet (); Tx. commit (); retu Rn ADDR;} finally {If (s! = NULL) s. close () ;}} static person query (int pid) {session S = NULL; transaction Tx = NULL; try {S = hibernateutil. getsession (); Tx = S. begintransaction (); person P = (person) s. get (person. class, pid); Tx. commit (); Return P;} finally {If (s! = NULL) s. close () ;}} static person add () {session S = NULL; transaction Tx = NULL; try {address addr1 = new address (); addr1.setstreet ("Add1 "); person p1 = new person (); p1.setname ("p1"); person P2 = new person (); p2.setname ("p2"); p1.setaddress (addr1); p2.setaddress (addr1 ); S = hibernateutil. getsession (); Tx = S. begintransaction (); S. save (addr1); S. save (P1); S. save (P2); Tx. commit (); Return P1;} finally {If (s! = NULL) S. Close ();}}}