hibernate操作无主键的table(复合主键)查询

这里记录hibernate中组合主键的annotation方式。

hibernate-annotations说明文档中有说到组合主键使用annotation的方式实现,如下几种

下面是定义组合主键的几种语法:

1.  将组件类注解为@Embeddable,并将组件的属性注解为@Id

2.  将组件的属性注解为@EmbeddedId

3.  将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id


我采用的是第二种,完美解决!


第二种方式比较简单

1.主键类,这个类不需要做任何的注解

package com.seed.lee.model;

import javax.persistence.Column;

/** 
* 这个类作为Person类的(组合主键)主键类 
* 
* @author Administrator 
* 
*/

public class PeopleUionPKID implements java.io.Serializable {

    private String firstName;

    private String secondName;

    @Column(length=20) 
    public String getFirstName() { 
        return firstName; 
    }

    public void setFirstName(String firstName) { 
        this.firstName = firstName; 
    } 
    @Column(length=20) 
    public String getSecondName() { 
        return secondName; 
    }

    public void setSecondName(String secondName) { 
        this.secondName = secondName; 
    }

    @Override 
    public boolean equals(Object obj) { 
        if(obj instanceof PeopleUionPKID){ 
            PeopleUionPKID pk=(PeopleUionPKID)obj; 
            if(this.firstName.equals(pk.firstName)&&this.secondName.equals(pk.secondName)){ 
                return true; 
            } 
        } 
        return false; 
    }

    @Override 
    public int hashCode() { 
        return super.hashCode(); 
    }

}

2.数据表映射的类(只需要在主键类的引用中添加@EmbeddedId就可以)

package com.seed.lee.model;

import javax.persistence.Column; 
import javax.persistence.EmbeddedId; 
import javax.persistence.Entity; 
import javax.persistence.Id;

@Entity 
public class Peopel {

    PeopleUionPKID uionPKID = new PeopleUionPKID();

    private int age;

    private String sex;

    private String job;

    @EmbeddedId 
    public PeopleUionPKID getUionPKID() { 
        return uionPKID; 
    }

    public void setUionPKID(PeopleUionPKID uionPKID) { 
        this.uionPKID = uionPKID; 
    }

    public int getAge() { 
        return age; 
    }

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

    @Column(length=4) 
    public String getSex() { 
        return sex; 
    }

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

    @Column(length=20) 
    public String getJob() { 
        return job; 
    }

    public void setJob(String job) { 
        this.job = job; 
    }

}
https://blog.csdn.net/renzhe_liubin/article/details/69388999  转载自

你可能感兴趣的:(hibernate操作无主键的table(复合主键)查询)