hibernate一对一映射示例

一、主键一对一
1.建表

DROP TABLE student;
DROP TABLE friend;

//主表,一个学生有多个朋友
CREATE TABLE t2.student( id INT NOT NULL auto_increment, name VARCHAR(100), sex INT, age INT, CONSTRAINT `PRIMARY` PRIMARY KEY(id) );
//从表
CREATE TABLE friend( id INT NOT NULL auto_increment, friend_id INT, name VARCHAR(100), sex INT, CONSTRAINT `PRIMARY` PRIMARY KEY(id), CONSTRAINT friend_ibfk_1
                    FOREIGN KEY(id) REFERENCES student(id) );

2.建model
2.1 Student.java

package test1.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = “student”, catalog = “t2”)
public class Student implements java.io.Serializable {

    private int id;
    private String name;
    private Integer sex;
    private Integer age;
    private Friend friend;

    public Student() {
    }

    public Student(int id) {
        this.id = id;
    }

    public Student(int id, String name, Integer sex, Integer age, Friend friend) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.friend = friend;
    }

    @Id
    
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = “id”, unique = true, nullable = false)
    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column(name = “name”, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = “sex”)
    public Integer getSex() {
        return this.sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    @Column(name = “age”)
    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY, mappedBy = “student”)
    public Friend getFriend() {
        return this.friend;
    }

    public void setFriend(Friend friend) {
        this.friend = friend;
    }
}

22Friend.java

package test1.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = “friend”, catalog = “t2”)
public class Friend implements java.io.Serializable {

    private Integer id;
    private Student student;
    private Integer friendId;
    private String name;
    private Integer sex;

    public Friend() {
    }

    public Friend(Student student) {
        this.student = student;
    }

    public Friend(Student student, Integer friendId, String name, Integer sex) {
        this.student = student;
        this.friendId = friendId;
        this.name = name;
        this.sex = sex;
    }

    @GenericGenerator(name = “generator”, strategy = “foreign”, parameters = @Parameter(name = “property”, value = “student”))
    @Id
    @GeneratedValue(generator = “generator”)

    @Column(name = “id”, unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public Student getStudent() {
        return this.student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Column(name = “friend_id”)
    public Integer getFriendId() {
        return this.friendId;
    }

    public void setFriendId(Integer friendId) {
        this.friendId = friendId;
    }

    @Column(name = “name”, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = “sex”)
    public Integer getSex() {
        return this.sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }
}

3.测试
package test1.r1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import test1.model.Friend;
import test1.model.Student;

public class HibernateOne2One1 {
    public static void main(String[] args) {
                System.out.println(“开始事务”);
                Configuration config = new Configuration().configure();
                SessionFactory sessionFactory = config.buildSessionFactory();
                Session session = sessionFactory.openSession();
                try {
                    Transaction tx = session.beginTransaction();

                    Student stu1 = new Student();
                    stu1.setName(“bkd2”);
                //    session.save(stu1);    
                    Friend fr1 = new Friend(stu1);
                    fr1.setName(“bkd1”);
                    session.save(fr1);
                    tx.commit();                  
                } catch (HibernateException e) {
                    e.printStackTrace();
                    session.getTransaction().rollback();
                } finally {
                    session.close();
                    sessionFactory.close();
                }
                System.out.println(“事务结束”);
    }
}

二、外键一对一
1.建表
drop table student;
drop table friend;
CREATE TABLE student (
    id INT NOT NULL auto_increment,
    name VARCHAR(100),
    sex INT,
    age INT,
    CONSTRAINT `PRIMARY` PRIMARY KEY (id)
);
CREATE TABLE friend (
    id INT NOT NULL auto_increment,
    friendId INT unique,
    name VARCHAR(100),
    sex INT,    
    CONSTRAINT `PRIMARY` PRIMARY KEY (id),
    CONSTRAINT friend_ibfk_1 FOREIGN KEY (friendId) REFERENCES student(id)
);

2.建model。
2.1Student.java
package test1.model;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = “student”, catalog = “t2”)
public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer sex;
    private Integer age;
    private Friend friend;

    public Student() {
    }

    public Student(int id, String name, Integer sex, Integer age, Friend friend) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.friend = friend;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = “id”, unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = “name”, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = “sex”)
    public Integer getSex() {
        return this.sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    @Column(name = “age”)
    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @OneToOne(fetch = FetchType.LAZY, mappedBy = “student”)
    public Friend getFriend() {
        return this.friend;
    }

    public void setFriend(Friend friend) {
        this.friend = friend;
    }
}

2.2Friend.java
package test1.model;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = “friend”, catalog = “t2”, uniqueConstraints = @UniqueConstraint(columnNames = “friendId”))
public class Friend implements java.io.Serializable {

    private Integer id;
    private Student student;
    private String name;
    private Integer sex;

    public Friend() {
    }

    public Friend(Student student, String name, Integer sex) {
        this.student = student;
        this.name = name;
        this.sex = sex;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = “id”, unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = “friendId”, unique = true)
    public Student getStudent() {
        return this.student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    @Column(name = “name”, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = “sex”)
    public Integer getSex() {
        return this.sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }
}

3.测试
package test1.r1;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import test1.model.Friend;
import test1.model.Student;

public class HibernateOne2One1 {

    public static void main(String[] args) {
        System.out.println(“开始事务”);
        Configuration config = new Configuration().configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        Session session = sessionFactory.openSession();
        try {
            Transaction tx = session.beginTransaction();

            Student stu1 = new Student();
            stu1.setName(“bkd2”);
            // session.save(stu1);
            Friend fr1 = new Friend(stu1,”fr1″,0);
            fr1.setName(“bkd1”);
            session.save(fr1);
            tx.commit();

        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            session.close();
            sessionFactory.close();
        }
        System.out.println(“事务结束”);

    }
}

三、双向外键一对一

修改下student.java关联到friend中的friendId即可。
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = “friendId”, unique = true)
    public Friend getFriend() {
        return this.friend;
    }

    public void setFriend(Friend friend) {
        this.friend = friend;
    }

Author: bkdwei