One-to-one primary key bidirectional ing and foreign key bidirectional ing in hibernate (1)

Source: Internet
Author: User

One-to-one primary key bidirectional ing and foreign key bidirectional ing in hibernate (1)

Primary Key Association focuses on two associated tables sharing a primary key value. In this example, a unit registers members in an online system.

1. member data is stored in the member table company, and each member's login account is saved in the table login;

2. One member has only one Logon account, and one Logon account only belongs to one member. The two tables have one-to-one relationship;

The company table is as follows:

The SQL statement for generating the company table is as follows:

 

CREATE TABLE `company` (`ID`  int(4) NOT NULL AUTO_INCREMENT ,`COMPANYNAME`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`LINKMAN`  char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`TELEPHONE`  char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`EMAIL`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,PRIMARY KEY (`ID`))

 

The login table is as follows:


The SQL statement used to generate a login table is as follows:

 


CREATE TABLE `login` ( `ID` int(4) NOT NULL , `LOGINNAME` char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , `LOGINPWD` char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , PRIMARY KEY (`ID`) )

 


 

The key of foreign key association is that two tables have different primary keys, but one table has a foreign key that references the primary key of the other table. That is, a non-primary key is another user's primary key is the foreign key of the table.

In this example:

1. The customer (Client) and customer Address (address) are one-to-one relationships associated with foreign keys, and change the Address table corresponding to the client table respectively.

2. client_address in the Client ing file of the Client class is the primary key of the corresponding table of the foreign key reference Address class, however, when setting the client_address attribute for multiple pairs in the Client ing file corresponding to the Client class, the unique value is set to true, that is, the foreign key is unique, that is, the one-to-one relationship.

The client table is as follows:

SQL language for generating client tables:

 

CREATE TABLE `client` (`ID`  int(4) NOT NULL AUTO_INCREMENT ,`CLIENTNAME`  char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`PHONE`  char(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`EMAIL`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`CLIENTADDRESSID`  int(4) NULL DEFAULT NULL ,PRIMARY KEY (`ID`),FOREIGN KEY (`CLIENTADDRESSID`) REFERENCES `address` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE,INDEX `CLIENTADDRESSID` (`CLIENTADDRESSID`) USING BTREE )
Note: The CLIENTADDRESSID here is a foreign key, and the foreign key must be set in the client table.

 



The address table is as follows:

 

 

CREATE TABLE `address` (`ID`  int(4) NOT NULL AUTO_INCREMENT ,`PROVINCE`  varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`CITY`  varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`STREET`  varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,`ZIPCODE`  char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,PRIMARY KEY (`ID`))

 

Hibernate. cfg. xml configuration file:

 

  
 
  
   
    org.hibernate.dialect.MySQLInnoDBDialect
   
   
    jdbc:mysql://localhost:3306/onetoone
   
   
    root
   
   
    123456
   
   
    com.mysql.jdbc.Driver
        
   
    true 
         
   
    true
    
   
    
     
      
     
    
   
  
 

One-to-one primary key bidirectional Association:

 

Company. java

 

Package com. hust. javabeans; import java. io. serializable; public class Company implements Serializable {/***/private Integer id; private String companyname; private String linkman; private String telephone; private String email; private Login login; // associate another class, that is, ensure that the Company object contains information about the Login object, reflecting a one-to-one Association of public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getCompanyname () {return companyname;} public void setCompanyname (String companyname) {this. companyname = companyname;} public String getLinkman () {return linkman;} public void setLinkman (String linkman) {this. linkman = linkman;} public String getTelephone () {return telephone;} public void setTelephone (String telephone) {this. telephone = telephone;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public Login getLogin () {return login;} public void setLogin (Login login) {this. login = login ;}}
Login. java

 

 

Package com. hust. javabeans; import java. io. serializable; public class Login implements Serializable {/***/private static final long serialVersionUID = 1L; private Integer id; private String loginname; private String loginpwd; private Company company Company; // associate another class, that is, ensure that the Login object contains Company object information, reflecting one-to-one Association of public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getLoginname () {return loginname;} public void setLoginname (String loginname) {this. loginname = loginname;} public String getLoginpwd () {return loginpwd;} public void setLoginpwd (String loginpwd) {this. loginpwd = loginpwd;} public Company getCompany () {return company;} public void setCompany (Company company Company) {this. company = company ;}}
Company. hbm. xml

 

 

 
    
       
           
         
        
        
        
        
                   
       
  
 
Login. hbm. xml

 

 

 
    
                  
             
    
     company          
           
                 
          
                          
         
  
 

One-to-one foreign key bidirectional Association:

 

Client. java

 

Package com. hust. javabeans; import java. io. serializable; public class Client implements Serializable {private Integer id; private String clientname; private String phone; private String email; private Address client_address; // associate with another class public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getClientname () {return clientname;} public void setClientname (String clientname) {this. clientname = clientname;} public String getPhone () {return phone;} public void setPhone (String phone) {this. phone = phone;} public String getEmail () {return email;} public void setEmail (String email) {this. email = email;} public Address getClient_address () {return client_address;} public void setClient_address (Address client_address) {this. client_address = client_address ;}}
Address. java

 

 

Package com. hust. javabeans; import java. io. serializable; public class Address implements Serializable {private Integer id; private String province; private String city; private String street; private String zipcode; private Client address_client; // associate another class public Integer getId () {return id;} public void setId (Integer id) {this. id = id;} public String getProvince () {return province;} public void setProvince (String province) {this. province = province;} public String getCity () {return city;} public void setCity (String city) {this. city = city;} public String getStreet () {return street;} public void setStreet (String street) {this. street = street;} public String getZipcode () {return zipcode;} public void setZipcode (String zipcode) {this.zip code = zipcode;} public Client getAddress_client () {return address_client ;} public void setAddress_client (Client address_client) {this. address_client = address_client ;}}
Client. hbm. xml

 

 

 
    
       
           
         
             
        
        
                   
      
  
 

 

The tag indicates one-to-one, and replicate-to-one should be written to the ing file corresponding to the table with foreign keys.

Address. hbm. xml

 

 
  
    
      
      
    
     
     
      
       
       
        
       
      
     
    
   
  
 

 

 

Access the database file OneOneDao. java

 

Package com. hust. dao; import org. hibernate. session; import org. hibernate. transaction; import com. hust. javabeans. client; import com. hust. javabeans. company; import SessionFactory. hibernateSessionFactory; public class OneOneDao {// Method for adding a member. Only the public void addCompany (Company company Company) {Session session = HibernateSessionFactory of the master prosecution is operated. getSession (); Transaction ts = null; try {ts = session. beginTransaction (); System. out. println (the addCompany method of oneonedao is executed, and the executed SQL :); session. save (company); System. out. println (completed by the addCompany method of oneonedao); ts. commit ();} catch (Exception ex) {ts. rollback (); System. out. println ([System Error] Error in addCompany method of oneonedao); ex. printStackTrace ();} finally {HibernateSessionFactory. closeSession () ;}}// obtain the member information public Company loadCompany (Integer id) {Session session = HibernateSessionFactory. getSession (); Transaction ts = null; Company company = null; try {ts = session. beginTransaction (); System. out. println (the loadCompany method of oneonedao is executed, and the executed SQL :); company = (Company) session. get (Company. class, id); System. out. println (the loadCompany method of oneonedao is completed); ts. commit ();} catch (Exception ex) {ts. rollback (); System. out. println ([System Error] An error occurred in the early oneonedao loadCompany method); ex. printStackTrace ();} finally {HibernateSessionFactory. closeSession () ;}return company ;}// add customer information. Only the public void addClient (Client client) {Session session = HibernateSessionFactory of the master prosecution is operated. getSession (); Transaction ts = null; try {ts = session. beginTransaction (); System. out. println (the addclient method of oneonedao is executed, and the executed SQL :); session. save (client); System. out. println (the addclient method of oneonedao is completed); ts. commit ();} catch (Exception ex) {ts. rollback (); System. out. println ([System Error] Error in addClient method of oneonedao); ex. printStackTrace ();} finally {HibernateSessionFactory. closeSession () ;}}// obtain the customer information public Client loadClient (Integer id) {Session session = HibernateSessionFactory. getSession (); Transaction ts = null; Client client = null; try {ts = session. beginTransaction (); System. out. println (the loadclient method of oneonedao is executed, and the executed SQL :); client = (Client) session. get (Client. class, id); System. out. println (the loadclient method of oneonedao is completed); ts. commit ();} catch (Exception ex) {ts. rollback (); System. out. println ([System Error] An error occurred in the loadclient method of oneonedao); ex. printStackTrace ();} finally {HibernateSessionFactory. closeSession () ;}return client ;}}
TestBean. java

 

 

Package com. hust. test; import com. hust. dao. oneOneDao; import com. hust. javabeans. address; import com. hust. javabeans. client; import com. hust. javabeans. company; import com. hust. javabeans. login; public class TestBean {OneOneDao oneonedao = new OneOneDao (); // obtain public void addCompany () {Company company Company = new Company (); login login = new Login (); login. setLoginname (tuke); login. setLoginpwd (123456); company. setCompanyname (SMILE); company. setLinkman (Zhang Shan); company. setTelephone (010-12345678); company. setEmail ([email protected]); // set the association relationship login Between PO objects. setCompany (company); company. setLogin (login); System. out. println (the addcompany method of testbean starts execution); // Add member information, save it to the database, save company to the database, and save login to the database. addCompany (company); System. out. println (the addcompany method of testbean is completed);} // obtain the member information public Company loadCompany (Integer id) {// obtain the company from the database and also obtain the login table record System. out. println (the loadcompany method of testbean starts execution); return oneonedao. loadCompany (id) ;}// Add the customer information public void addClient () {Client client = new Client (); Address address = new Address (); address. setProvince (Hubei province); address. setCity (Wuhan); address. setStreet (linjiang Avenue); address. setzip code (100083); client. setClientname (Li Xiang); client. setPhone (027-76866876); client. setEmail ([email protected]); // set the address of the association between PO objects. setAddress_client (client); client. setClient_address (address); System. out. println (the addclient method of testbean starts execution); // Add customer information, save it to the database, save the client to the database, and save the address to the database. addClient (client); System. out. println (the addclient method of testbean is completed);} // obtain the customer information public Client loadClient (Integer id) {System. out. println (the loadclient method of testbean starts execution); return oneonedao. loadClient (id );}}
The result is displayed as follows:

 


The SQL statement printed on the console is:

 

Testbean addcompany method execution starts log4j: WARN No appenders cocould be found for logger (org. hibernate. cfg. environment ). log4j: WARN Please initialize the log4j system properly. the addCompany method of oneonedao executes the SQL statement Hibernate: insert into company (COMPANYNAME, LINKMAN, TELEPHONE, EMAIL) values (?, ?, ?, ?) The addCompany method of oneonedao completes Hibernate: insert into login (LOGINNAME, LOGINPWD, ID) values (?, ?, ?) When the addcompany method of testbean is executed completely // when the primary key is associated, the two insert statements are not the addclient method of testbean that has been executed consecutively. The addclient method of oneonedao is executed. The executed SQL: Hibernate: insert into address (PROVINCE, CITY, STREET, ZIPCODE) values (?, ?, ?, ?) Hibernate: insert into client (CLIENTNAME, PHONE, EMAIL, CLIENTADDRESSID) values (?, ?, ?, ?) When the addclient method of oneonedao completes the execution of the addclient method of testbean // when the foreign key Association is completed, the loadcompany Method of Two insert statements testbean is executed consecutively and the loadCompany method of oneonedao is executed. The executed SQL: hibernate: select company0 _. ID as ID2_1 _, company0 _. COMPANYNAME as COMPANYN2_2_1 _, company0 _. LINKMAN as LINKMAN2_1 _, company0 _. TELEPHONE as TELEPHONE2_1 _, company0 _. EMAIL as EMAIL2_1 _, login1 _. ID as ID3_0 _, login1 _. LOGINNAME as LOGINNAME3_0 _, login1 _. LOGINPWD as LOGINPWD3 _ 0 _ from company company0 _ left outer join login login1 _ on company0 _. ID = login1 _. ID where company0 _. ID =? The loadCompany method of oneonedao completes the loadclient method execution of testbean and starts the loadclient method execution of oneonedao. The executed SQL is Hibernate: select client0 _. ID as ID1_0 _, client0 _. CLIENTNAME as CLIENTNAME1_0 _, client0 _. PHONE as PHONE1_0 _, client0 _. EMAIL as EMAIL1_0 _, client0 _. CLIENTADDRESSID as clientad5_defaults 0 _ from client client0 _ where client0 _. ID =? Hibernate: select address0 _. ID as ID0_1 _, address0 _. PROVINCE as PROVINCE0_1 _, address0 _. CITY as CITY0_1 _, address0 _. STREET as STREET0_1 _, address0 _. ZIPCODE as ZIPCODE0_1 _, client1 _. ID as ID1_0 _, client1 _. CLIENTNAME as CLIENTNAME1_0 _, client1 _. PHONE as PHONE1_0 _, client1 _. EMAIL as EMAIL1_0 _, client1 _. CLIENTADDRESSID as clientad5_defaults 0 _ from address address0 _ left outer join client client1 _ on address0 _. ID = client1 _. CLIENTADDRESSID where address0 _. ID =? Hibernate: select client0 _. ID as ID1_0 _, client0 _. CLIENTNAME as CLIENTNAME1_0 _, client0 _. PHONE as PHONE1_0 _, client0 _. EMAIL as EMAIL1_0 _, client0 _. CLIENTADDRESSID as clientad5_defaults 0 _ from client client0 _ where client0 _. CLIENTADDRESSID =? The loadclient method of oneonedao is complete.


 

 






 

 

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.