Hibernate 一對一關聯映射

來源:互聯網
上載者:User

標籤:blog   io   os   ar   java   for   sp   div   on   

package com.entity;import javax.persistence.Entity;import javax.persistence.OneToOne;@Entitypublic class Husband extends BaseEntity {@OneToOne(mappedBy = "husband")private Wife wife;public Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}

husband.java

package com.entity;import javax.persistence.Entity;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;@Entitypublic class Wife extends BaseEntity {private String name;@ManyToOne@JoinColumn(name="husband_id",unique=true)private Husband husband;public String getName() {return name;}public void setName(String name) {this.name = name;}public Husband getHusband() {return husband;}public void setHusband(Husband husband) {this.husband = husband;}}

 wife.java

 

package com;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.entity.Food;import com.entity.Husband;import com.entity.User;import com.entity.Wife;import com.entity.student.Classes;import com.entity.student.Teacher;public class Test1 {private Session s;private Transaction tran;@Beforepublic void before(){s=HibernateUtils.getSession();tran=s.beginTransaction();}public void test(){User user=(User)s.get(User.class,7);//持久太//user.setUsername("xixixi");//修改後不用save直接提交也可儲存tran.commit();s.clear();//使對象與session沒有關係 , 脫離持久太//把游離態的user變成持久態tran=s.beginTransaction();s.update(user);user.setPassword("789");tran.commit();//將對象變成順時太tran=s.beginTransaction();s.delete(user);tran.commit();}public void one2one(){Husband h=new Husband();Wife w=new Wife();//建立兩個瞬時對象h.setName("xiaoming");w.setName("baby");w.setHusband(h);s.save(w);s.save(h);}@Testpublic void one2oneQuery(){Husband h=(Husband)s.get(Husband.class, 2);System.out.println(h.getName()+"-------------"+h.getWife().getName());}@After public void after(){tran.commit(); HibernateUtils.closeSession(s);}}

 test1.java

Hibernate 一對一關聯映射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.