欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(4)OneToOne联合单向外键关联: @JoinColumns

程序员文章站 2022-04-11 17:41:36
...

Wife中是联合主键
在利用@IdClass(WifePK.class)方式时,主键类(WifePK)中的属性和Wife中的属性要相同

@Entity
@IdClass(WifePK.class)
public class Wife {


    private int id;
    private String name;


    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }


    @Id
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }   
}

主键类


public class WifePK implements Serializable{

    private int id;
    private String name;
    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;
    }

    @Override
    public int hashCode() {

        return id*10+name.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof WifePK){
            WifePK pk=(WifePK) obj;
            if(pk.id==this.id&&pk.name==this.name)
            {
                return false;
            }
        }
        return true;
    }
}

husband类

@Entity
public class Husband {

    private int id;
    private String name;
    private int age;
    private Wife wife;

    @Id
    @GeneratedValue

    /*
     * 使用@Id注解可以将属性标识为id,一般情况让hibernate自动生成策略来生成主键
     * 这种写法:会自动根据数据库类型,生成不同的自增长。在mysql中是auto_increment
     * 在oracle中是sequence
     * 所以主键要有两个注解
     */
    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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @OneToOne//Husband 与Wife 是一一对应关系
    @JoinColumns(
    {
            @JoinColumn(name="wifeid",referencedColumnName ="id") ,
            @JoinColumn(name="wifeName",referencedColumnName ="name") 
    }
)
    public Wife getWife() {
        return wife;
    }
    public void setWife(Wife wife) {
        this.wife = wife;
    }

}

@JoinColumns:即 @JoinColumn数组,定义了关联的组合外键,显式指明referencedColumnNames是种好的实践方式。若不指定,默认生成策略是wi_id wi_name ,@JoinColumn设置name,只是重命名而已

相关标签: entity