一对一单向外键关联

新建两个类,Husband.java和Wife.java两个类的id号是一一对应的,用面向对象的方式是加引用,单向关联就是只在其中一个加引用,在数据库中怎么设计呢?

第一种是在husband里面加一个外键,在生成husband的时候,必须去wife里面找一下这个id有没有,这叫主键关联,这样就保证的一对一的关系了。

第二种,再加一个字段如wife_id,称为外键关联。以wife为主导,必须wife先有了id,wifeid才能有值。

第三种,使用中间表,关联表。里面写husband_id,wife_id。

husband.java

package hjj.lch.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Husband {
    private int id;
    private String name;
    private Wife wife;
    
    @Id
    @GeneratedValue
    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
    public Wife getWife() {
        return wife;
    }
    public void setWife(Wife wife) {
        this.wife = wife;
    }
    

}

Wife.java

package hjj.lch.hibernate.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Wife {
    private int id;
    private String name;
    
    @Id
    @GeneratedValue
    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;
    }
    

}

测试

@Test
    public void testSchemaExport(){
        new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
    }

后台结果:

12:30:11,114  INFO SchemaExport:226 - Running hbm2ddl schema export
12:30:11,114 DEBUG SchemaExport:242 - import file not found: /import.sql
12:30:11,114  INFO SchemaExport:251 - exporting generated schema to database
12:30:11,274 DEBUG SchemaExport:377 -
    alter table Husband
        drop
        foreign key FKAEEA401BD4D6367E
12:30:11,454 DEBUG SchemaExport:377 -
    drop table if exists Husband
12:30:11,474 DEBUG SchemaExport:377 -
    drop table if exists Wife
12:30:11,504 DEBUG SchemaExport:377 -
    create table Husband (
        id integer not null auto_increment,
        name varchar(255),
        wife_id integer,
        primary key (id)
    )
12:30:11,584 DEBUG SchemaExport:377 -
    create table Wife (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )
12:30:11,644 DEBUG SchemaExport:377 -
    alter table Husband
        add index FKAEEA401BD4D6367E (wife_id),
        add constraint FKAEEA401BD4D6367E
        foreign key (wife_id)
        references Wife (id)
12:30:11,815  INFO SchemaExport:268 - schema export complete

使用@JoinColumn(name="wifeId")可以改变属性名

 

在xml里面单向关联怎么配?

<many-to-one name="student" column="studentId" unique="true"></many-to-one>

因为设置了unique="true",所以它就是一对一了。

 

 

posted @ 2013-12-09 13:05  李鬼989  阅读(315)  评论(0编辑  收藏  举报