码迷,mamicode.com
首页 > Web开发 > 详细

hibernate学习(设计一对一 关系 映射)

时间:2015-12-27 13:26:20      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

//主表
package org.crazy.app.domain;
import javax.persistence.*;
@Entity
@Table(name="person_inf")
public class Person {
    @Id
    @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private int age;
    @OneToOne(targetEntity=Address.class,mappedBy="person")
    private Address address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
}

//-----------------------------------
package org.crazy.app.domain;

import javax.persistence.*;

@Entity
@Table(name="address_inf")
public class Address {
    @Id
    @Column(name="address_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer addressId;
    private String addressDetail;
    @OneToOne(targetEntity=Person.class)
    @JoinColumn(name="person_id", referencedColumnName="person_id",unique=true)
    private Person person;
    public Integer getAddressId() {
        return addressId;
    }
    public void setAddressId(Integer addressId) {
        this.addressId = addressId;
    }
    
    
    public Address(String addressDetail) {
        this.addressDetail = addressDetail;
    }
    public String getAddressDetail() {
        return addressDetail;
    }
    public void setAddressDetail(String addressDetail) {
        this.addressDetail = addressDetail;
    }
    public Person getPerson() {
        return person;
    }
    public void setPerson(Person person) {
        this.person = person;
    }
    
    
}

 

 

    public static void main(String[] args) {
        testCascase();
    }
    public static void testCascase(){
        Session session=HibernateUtil.currentSession();
        Transaction tx=session.beginTransaction();
        Person p=new Person();
        p.setName("潘庆强");
        Address a=new Address("宜山路333号");
        p.setAddress(a);a.setPerson(p);
        session.save(p);
        session.save(a);
        tx.commit();
        HibernateUtil.closeSession();
    }

 

 

技术分享

hibernate学习(设计一对一 关系 映射)

标签:

原文地址:http://www.cnblogs.com/panqingqiang/p/5079814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!