一对一双向外键联合主键(annotation方式)

主键类
package org.hibernate.tutorial.domain;


public class WifePK implements Serializable {
	private int id;
	private String name;
	
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}



设置对象主键

@Entity
@IdClass(WifePK.class)
public class Wife {
	private int id;
	private String name;
	private String age;
	
	
	@Id
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Id
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
}



设置关联
@Entity
public class Husband {
	private int id;
	private String name;
	private Wife wife;
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	
	@OneToOne
	@JoinColumns(
			{
				@JoinColumn(name="wifeId",referencedColumnName="id"),
				@JoinColumn(name="wifeName",referencedColumnName="name")
			}
	)
	public Wife getWife() {
		return wife;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	
}




hibernate.hb.xml配置和测试
引用

<mapping class="org.hibernate.tutorial.domain.Husband"/>
<mapping class="org.hibernate.tutorial.domain.Wife"/>

public class OneToOneORMappingTest {
	public static void main(String[] args) {
		new SchemaExport(new AnnotationConfiguration().configure("/hibernate.cfg.xml")).create(true, false);
	}
}


结果
alter table Husband 
        drop 
        foreign key FK_sdshifqwgidsm93jdh5kfl0e4

    drop table if exists Husband

    drop table if exists Wife

    create table Husband (
        id integer not null auto_increment,
        name varchar(255),
        wifeId integer,
        wifeName varchar(255),
        primary key (id)
    )

    create table Wife (
        id integer not null,
        name varchar(255) not null,
        age varchar(255),
        primary key (id, name)
    )

    alter table Husband 
        add index FK_sdshifqwgidsm93jdh5kfl0e4 (wifeId, wifeName), 
        add constraint FK_sdshifqwgidsm93jdh5kfl0e4 
        foreign key (wifeId, wifeName) 
        references Wife (id, name)

你可能感兴趣的:(annotation)