One-to-one association of enitybean

Source: Internet
Author: User

I. Engineering architecture:

Engineering Resources: http://download.csdn.net/detail/u012750578/7660633

Ii. Beans. xml configuration

<? XML version = "1.0" encoding = "UTF-8"?> <! -- Annotation-based http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd http://www.springframework.org/schema/beans --> <beans xmlns = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsi = "http://www.springframework.org/schema/context" xmlns: context = "http://www.springframework.org" xmlns: AOP =/ Schema/AOP "xmlns: Tx =" http://www.springframework.org/schema/tx "xsi: schemalocation =" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-ao P-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd "> <context: annotation-config/> <context: component-scan base-package =" com. entity "> </Context: component-scan> <bean id =" da Tasource "class =" org. apache. commons. DBCP. basicdatasource "Destroy-method =" close "> <property name =" driverclassname "value =" oracle. JDBC. driver. oracledriver "/> <property name =" url "value =" JDBC: oracle: thin: @ localhost: 1521: orcl11g "/> <property name =" username "value =" entity "/> <property name =" password "value =" entity "/> <! -- Initial value when the connection pool starts --> <property name = "initialsize" value = "1"/> <! -- Maximum value of the connection pool --> <property name = "maxactive" value = "500"/> <! -- Maximum idle value. after a peak time, the connection pool can slowly release a portion of connections that are no longer in use, until maxidle --> <property name = "maxidle" value = "2"/> <! -- Minimum idle value. when the number of idle connections is less than the threshold value, the connection pool will pre-apply for some connections, so that you do not have time to apply when the peak traffic arrives --> <property name = "minidle" value = "1"/> </bean> <! -- Org. springframework. orm. hibernate3.annotation. annotationsessionfactorybean annotation-based sessionfactroy --> <bean id = "sessionfactory" class = "org. springframework. orm. hibernate3.annotation. annotationsessionfactorybean "name =" sessionfactory "> <property name =" datasource "ref =" datasource "/> <property name =" hibernateproperties "> <value> hibernate. dialect = org. hibernate. dialect. oracledialecthib.pdf. hbm2ddl. auto = UPDA Tehibernate. show_ SQL = truehibernate. format_ SQL = truehibernate. cache. use_second_level_cache = truehibernate. cache. use_query_cache = falsehibernate. cache. provider_class = org. hibernate. cache. ehcacheprovider </value> </property> <! -- Annotatedclasses --> <property name = "annotatedclasses"> <list> <value> COM. entity. one2one. bean. customer </value> <value> COM. entity. one2one. bean. referee </value> <value> COM. entity. one2one. bean. customerprimary </value> <value> COM. entity. one2one. bean. refereeprimary </value> </List> </property> </bean> <bean id = "txmanager" class = "org. springframework. orm. hibernate3.hibernatetransactionmanager "> <property name =" sessionfactory "ref =" sessionfactory "/> </bean> <TX: annotation-driven transaction-Manager =" txmanager "/> </beans>


3. One-to-many relationship based on shared primary keys

1. entitybean

Refereeprimary:

@ Entity @ table (name = "t_primary_referee") public class refereeprimary {private int ID; private string name; private customerprimary customer; @ onetoone @ primarykeyjoincolumnpublic customerprimary getcustomer () {return customer ;} public void setcustomer (customerprimary customer) {This. customer = Customer;} // when using a one-to-one ing based on the primary key, you must change the primary key generation policy to foreign // The customer @ ID @ generatedvalue (generator = "pkgenerator") corresponding to the property ") @ genericgenerator (name = "pkgenerator", strategy = "foreign", [email protected] (Name = "property", value = "customer") 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 ;}}

Customerprimary:

@ Entity @ table (name = "t_primary_customer") public class customerprimary {private int ID; private string name; private refereeprimary referee; @ ID // indicates that this ID attribute is a foreign key, and dependent on the ID attribute value (primary key value) of the object bean corresponding to the customer attribute @ genericgenerator (name = "genericgenerator", strategy = "sequence ", parameters = {@ parameter (value = "seq_primary_customer", name = "sequence")}) @ generatedvalue (generator = "genericgenerator") Public int GETID () {return ID ;} /*** Note: Because the ID auto-increment type of the t_referee table has been removed and the class depends on the ID field value of the t_customers table *, the referee object cannot be directly persisted, while the customer object is persisted, the container automatically persists the referee ** @ Param ID */Public void setid (int id) {This. id = ID;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} // Shared primary key @ onetoone (cascade = cascadetype. all) @ primarykeyjoincolumnpublic refereeprimary getreferee () {return referee;} public void setreferee (refereeprimary referee) {This. referee = referee ;}}

2. Service

@ Service ("customerprimaryservice") @ transactionalpublic class customerprimaryservice {@ resourceprivate sessionfactory; // test and save public void saveprimary () {customerprimary customer = new customerprimary (); customer. setname ("Microsoft"); refereeprimary referee = new refereeprimary (); referee. setname ("Zhao Jun"); // join // use a primary key-based one-time pair: only foreign key providers can save the associated customer. setreferee (referee); referee. setcustomer (customer); // first save the non-foreign key side, and first save the primary key side sessionfactory. getcurrentsession (). persist (customer); // store the foreign key again, because the foreign key must reference the primary key value sessionfactory without the foreign key. getcurrentsession (). persist (referee);} // obtain public mermerprimary getcustomerprimary (int id) {return (customerprimary) sessionfactory Based on the ID. getcurrentsession (). get (customerprimary. class, 1);} // obtain public refereeprimary getrefereeprimary (int id) {return (refereeprimary) sessionfactory Based on the ID. getcurrentsession (). get (refereeprimary. class, 1) ;}// remove an association // when a primary key-based pair is used, neither party can remove the association public void removerelationprimary () {customerprimary customer = (customerprimary) sessionfactory. getcurrentsession (). get (customerprimary. class, 1); customer. setreferee (null); sessionfactory. getcurrentsession (). persist (customer);} // remove an association // when a primary key-based pair is used, neither party can remove the association public void removerelationnoprimary () {refereeprimary referee = (refereeprimary) sessionfactory. getcurrentsession (). get (refereeprimary. class, 1); referee. setcustomer (null); sessionfactory. getcurrentsession (). persist (referee);} // because refereeprimary is a non-foreign key statement and cannot maintain the association, if there is an associated customer When deleting refereeprimary, an exception will be thrown // because the customerprimary ID has the idpublic void deletenoforeign () {sessionfactory that references refereeprimary. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (refereeprimary. class, 1);} // Delete the customerprimary and refereeprimary record public void deleteforeign () {sessionfactory. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (customerprimary. class, 1);} // test the deletion of Public void deleteall () {// Delete sessionfactory with a foreign key first. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (customerprimary. class, 2);} // obtain the test list information @ suppresswarnings ("unchecked") public list <customerprimary> getcustomerprimarys () {return sessionfactory. getcurrentsession (). createquery ("from mermerprimary "). list ();} // obtain the list information by testing @ suppresswarnings ("unchecked") public list <refereeprimary> getrefereeprimarys () {return sessionfactory. getcurrentsession (). createquery ("from refereeprimary "). list ();}}

3. JUnit Testing

Public class customerprimaryservicetest {Private Static customerprimaryservice; @ beforeclasspublic static void setupbeforeclass () throws exception {try {applicationcontext = new classpathxmlapplicationcontext ("beans. XML "); customerprimaryservice = (customerprimaryservice) applicationcontext. getbean ("customerprimaryservice");} catch (runtimeexception e) {e. printstacktrace () ;}}// test and save @ testpublic void testsaveprimary () {customerprimaryservice. saveprimary ();} // obtain the association value through the test @ test public void testgetprimarycustomer () {customerprimary customer = customerprimaryservice. getcustomerprimary (1); system. out. println (customer. getreferee (). getname ();} // obtain the association value for the test @ test public void testgetprimaryreferee () {refereeprimary referee = customerprimaryservice. getrefereeprimary (1); system. out. println (referee. getcustomer (). getname ();} // test the removal link @ testpublic void testremoverelationprimary () {customerprimaryservice. removerelationprimary ();} // test the removal link @ testpublic void testremoverelationnoprimary () {customerprimaryservice. removerelationnoprimary ();} // No foreign key. You cannot delete @ testpublic void testdeletenoforeign () {customerprimaryservice. deletenoforeign ();} // a foreign key can be deleted. Deleting is to delete the information of two tables @ testpublic void testdeleteforeign () {customerprimaryservice. deleteforeign ();} // obtain the list information by testing @ testpublic void testgetcustomerprimarys () {for (customerprimary C: customerprimaryservice. getcustomerprimarys () {system. out. println (C. getname () ;}}// obtain the list information for the test @ testpublic void testgetprimaryreferees () {for (refereeprimary R: customerprimaryservice. getrefereeprimarys () {system. out. println (R. getname ());}}}

4. One-to-one association based on foreign keys)
1. entitybean

@ Entity @ table (name = "t_customer") Public Class Customer {private int ID; private string name; private referee; @ ID @ genericgenerator (name = "genericgenerator ", strategy = "sequence", parameters = {@ parameter (value = "seq_t_customer", name = "sequence")}) @ generatedvalue (generator = "genericgenerator") 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;}/*** default foreign key name referee_id * @ onetoone * Public referee getreferee () {return referee ;} * @ return * // ***/use the new foreign key name: referee1_id * @ onetoone @ joincolumn (name = "referee1_id") Public referee getreferee () {return referee ;} * @ return */@ onetoone @ joincolumn (name = "referee_id") Public referee getreferee () {return referee;}/*** as shown in the code above, the getreferee method uses @ onetoone to set * when the customer object is loaded, the referee object will be loaded at the same time, the default foreign key field is the referee attribute name + "_" + id * in the customer class, that is, referee_id * @ Param referee */Public void setreferee (referee) {This. referee = referee ;}}

REFEREE:

@Entity@Table(name="t_referee")public class Referee {private int id;private String name;private Customer customer;@Id@GenericGenerator(name = "GenericGenerator", strategy = "sequence",parameters = { @Parameter(value = "seq_t_referee", name = "sequence") })@GeneratedValue(generator="GenericGenerator")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;}@OneToOne(mappedBy="referee")public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}}

2. Service

@ Service ("customerservice") @ transactionalpublic class customerservice {@ resourceprivate sessionfactory; Public void saveforgin () {customer = new customer (); customer. setname ("Microsoft"); referee = new referee (); referee. setname ("Zhao Jun"); customer. setreferee (referee); referee. setcustomer (customer); // save sessionfactory without foreign keys first. getcurrentsession (). persist (referee); sessionfactory. getcurrentsession (). persist (customer);} public customer getcustomer (int id) {return (customer) sessionfactory. getcurrentsession (). get (customer. class, ID);} public referee getreferee (int id) {return (referee) sessionfactory. getcurrentsession (). get (referee. class, ID);}/*** foreign key can maintain the link to remove the link */Public void removerelationforeign () {customer = (customer) sessionfactory. getcurrentsession (). get (customer. class, 1); customer. setreferee (null); sessionfactory. getcurrentsession (). persist (customer);}/*** the relationship cannot be maintained because there is no foreign key. Therefore, when deleting a referee, if there is an associated customer, an exception will be thrown, causing both parties to fail to delete */Public void removerelationnoforeign () {sessionfactory. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (referee. class, 1);}/*** foreign key can maintain the relationship, * removes the association first * deletes the foreign key, */Public void removerelationforeignone () {sessionfactory. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (customer. class, 1);} public void deletenoforeignone () {// Delete sessionfactory with a foreign key first. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (referee. class, 1);} public void deleteforeignone () {// Delete sessionfactory with a foreign key first. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (customer. class, 1);} public void deleteforeigntow () {// Delete sessionfactory with a foreign key first. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (customer. class, 1); // Delete sessionfactory without foreign keys. getcurrentsession (). delete (sessionfactory. getcurrentsession (). get (referee. class, 1) ;}@ suppresswarnings ("unchecked") public list <customer> getmers MERs () {return sessionfactory. getcurrentsession (). createquery ("from customer "). list () ;}@ suppresswarnings ("unchecked") public list <referee> getreferees () {return sessionfactory. getcurrentsession (). createquery ("from referee "). list ();}}

3. JUnit Testing

Public class customerservicetest {Private Static customerservice; @ beforeclasspublic static void setupbeforeclass () throws exception {try {applicationcontext = new classpathxmlapplicationcontext ("beans. XML "); customerservice = (customerservice) applicationcontext. getbean ("customerservice");} catch (runtimeexception e) {e. printstacktrace () ;}}// test and save @ testpublic void testsaveforgin () {customerservice. saveforgin ();} // test to obtain the attribute value of the associated object @ testpublic void testgetcustomer () {customer = customerservice. getcustomer (1); system. out. println (customer. getreferee (). getname ();} // test to obtain the attribute value of the associated object @ testpublic void testgetreferee () {referee = customerservice. getreferee (1); system. out. println (referee. getcustomer (). getname ();} // test the removal of a link. // The foreign key can maintain the link and remove the link @ testpublic void testremoverelationforeign () {customerservice. removerelationforeign ();} // test the function of removing a link from a link. // No foreign key exists. The link cannot be maintained. Therefore, if a referee is deleted, an exception will be thrown, causing both parties to fail to delete @ testpublic void testremoverelationnoforeign () {customerservice. removerelationnoforeign ();} // You cannot delete @ testpublic void testdeletenoforeignone () {customerservice. deletenoforeignone ();} // deletes a foreign key. You can delete @ testpublic void testdeleeteforeignone () {customerservice. deleteforeignone () ;}// Delete the foreign key first, and then delete the non-foreign key @ testpublic void testdeleteforeigntow () {customerservice. deleteforeigntow ();} @ testpublic void testgetreferees () {for (referee R: customerservice. getreferees () {system. out. println (R. getname () ;}@ testpublic void testgetcustomers () {for (customer C: customerservice. getcustomers () {system. out. println (C. getname ());}}}




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.