如何在Hibernate中将主键从主表复制到子表

时间:2019-01-31 07:53:09

标签: java hibernate java-8

如何在Hibernate中将主键(共享密钥)从主表复制到子表。我正在尝试进行单向映射(Employee引用了Address,反之亦然)。

其他信息: 休眠依赖项:

<dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.1.Final</version>
</dependency>

我有Employee类和Address实体,如下所示。我试图在Employee实体中为Address实体生成主键。

但是,我看到employeeId表中的ADDRESS总是由休眠生成为0(我希望可以将其复制)。我猜我在使用@PrimaryKeyJoinColumn@MapsId时做错了。我试图添加两者,或在其中添加一个,但没有运气。

以下是该模式对应的表:

create table EMPLOYEE(
EMPLOYEE_ID int auto_increment,
NAME varchar(100),
SALARY double,
primary key(EMPLOYEE_ID)
);



create table ADDRESS
(
EMPLOYEE_ID int references EMPLOYEE.EMPLOYEE_ID,
STREET_NAME varchar(40),
CITY_NAME varchar(40),
STATE_NAME varchar(40),
ZIP_CODE varchar(40),
primary key(EMPLOYEE_ID)
);

实体映射如下:

Employee.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

    @Id
    @Column(name = "EMPLOYEE_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "SALARY")
    private double salary;

    @OneToOne
    @JoinColumn(name="EMPLOYEE_ID")
   @MapsId
    //@PrimaryKeyJoinColumn
    private Address address;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getSalary() {
        return salary;
    }

    public Employee setSalary(double salary) {
        this.salary = salary;
        return this;
    }

    public Address getAddress() {
        return address;
    }

    public Employee setAddress(Address address) {
        this.address = address;
        return this;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", address=" + address +
                '}';
    }
}

Address.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MapsId;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "ADDRESS")
public class Address implements Serializable {

    @Id
    @Column(name = "EMPLOYEE_ID")
    private int id;

    @Column(name = "STREET_NAME")
    private String streetName;

    @Column(name = "CITY_NAME")
    private String cityName;

    @Column(name = "STATE_NAME")
    private String stateName;

    @Column(name = "ZIP_CODE")
    private String zipCode;

    public int getId() {
        return id;
    }

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

    public String getStreetName() {
        return streetName;
    }

    public Address setStreetName(String streetName) {
        this.streetName = streetName;
        return this;
    }

    public String getCityName() {
        return cityName;
    }

    public Address setCityName(String cityName) {
        this.cityName = cityName;
        return this;
    }

    public String getStateName() {
        return stateName;
    }

    public Address setStateName(String stateName) {
        this.stateName = stateName;
        return this;
    }

    public String getZipCode() {
        return zipCode;
    }

    public Address setZipCode(String zipCode) {
        this.zipCode = zipCode;
        return this;
    }

    @Override
    public String toString() {
        return "Address{" +
                "id=" + id +
                ", streetName='" + streetName + '\'' +
                ", cityName='" + cityName + '\'' +
                ", stateName='" + stateName + '\'' +
                ", zipCode='" + zipCode + '\'' +
                '}';
    }
}

保存方法:

  public Employee save(Employee employee){

        Session session = HibernateUtil.buildSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        session.save(address); // Should I do this?            
        session.save(employee);
        transaction.commit();
        return employee;
    }

3 个答案:

答案 0 :(得分:1)

您需要在复制主键值的实体上对关联进行建模。如果这样做,则可以使用@MapsId注释关联。

在您的示例中,Employee实体的主键是使用IDENTITY strategy生成的,并且Address实体应使用相同的值。为此,您需要在Address实体上对one-to-one association进行建模。您可以使用双向或单向关联映射。

如果您更喜欢单向的,则可以使用与address实体的Employee属性相同的映射注释。然后,您当然需要随后删除address属性;)

在双向映射中,您的Employee实体看起来像这样:

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

    @Id
    @Column(name = "EMPLOYEE_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "SALARY")
    private double salary;

    @OneToOne
    @JoinColumn(name="EMPLOYEE_ID")
    private Address address;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getSalary() {
        return salary;
    }

    public Employee setSalary(double salary) {
        this.salary = salary;
        return this;
    }

    public Address getAddress() {
        return address;
    }

    public Employee setAddress(Address address) {
        this.address = address;
        return this;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", address=" + address +
                '}';
    }
}

这是Address实体。此映射的重要部分是一对一关联上的@MapsId注释。

@Entity
@Table(name = "ADDRESS")
public class Address implements Serializable {

    @Id
    @Column(name = "EMPLOYEE_ID")
    private int id;

    @Column(name = "STREET_NAME")
    private String streetName;

    @Column(name = "CITY_NAME")
    private String cityName;

    @Column(name = "STATE_NAME")
    private String stateName;

    @Column(name = "ZIP_CODE")
    private String zipCode;

    @OneToOne(mappedBy="address")
    @MapsId
    private Employee employee

    public int getId() {
        return id;
    }

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

    public String getStreetName() {
        return streetName;
    }

    public Address setStreetName(String streetName) {
        this.streetName = streetName;
        return this;
    }

    public String getCityName() {
        return cityName;
    }

    public Address setCityName(String cityName) {
        this.cityName = cityName;
        return this;
    }

    public String getStateName() {
        return stateName;
    }

    public Address setStateName(String stateName) {
        this.stateName = stateName;
        return this;
    }

    public String getZipCode() {
        return zipCode;
    }

    public Address setZipCode(String zipCode) {
        this.zipCode = zipCode;
        return this;
    }

    public Employee getEmployee() {
        return employee;
    }

    public void setEmployee(Employee emp) {
        this.employee = emp;
    }

    @Override
    public String toString() {
        return "Address{" +
                "id=" + id +
                ", streetName='" + streetName + '\'' +
                ", cityName='" + cityName + '\'' +
                ", stateName='" + stateName + '\'' +
                ", zipCode='" + zipCode + '\'' +
                '}';
    }
}

如您所见,我删除了@PrimaryKeyJoinColumn注释。仅当您的实体映射到2个数据库表时使用。如果您使用inheritance strategy JOINED或使用旧数据库并需要map 2 tables to the same entity就是这种情况。

答案 1 :(得分:0)

我认为您不需要手动复制主键。如果您使用的是像休眠这样的ORM,则实际上需要将实体对象(在您的情况下为Address实体对象)传递给要为其创建1-1映射的类对象(在您的情况下为Employee)。 Hibernate将自动使用实体主键(地址主键)填充映射实体中的列(Employee表中的address列)。您可以在此处查看与您的案例非常相似的示例: https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-one-to-one-using-annotations-1.html

如果看到的话,它们在地址表中有一个主键,即addressId。现在在学生班级中,他们有一个地址类型的字段,该字段被标记为@OneToOne,表示其映射。现在,在学生类构造函数中,我们正在传递地址对象。现在,在主函数中,如果您看到的是,我们仅保存了学生对象(而不是地址对象)。现在,当保存交易时,休眠将知道,首先创建地址实体,因为学生实体依赖该地址实体,然后使用创建的地址实体的主键保存学生实体。

现在,当您获取学生实体时,hibernate还将在查看学生表中的addressId的同时自动获取地址实体。希望能帮助到你。让我知道是否需要进一步澄清。

答案 2 :(得分:0)

我已经映射了如下实体:

Employee.java中的代码中查看以下内容

 @OneToOne(fetch = FetchType.LAZY)
   @PrimaryKeyJoinColumn
    private Address address;

Employee.java

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {

    public Employee(){

    }
    public Employee(String name){
        this.name = name;
    }

    public Employee(String name,double salary){
        this.name = name;
        this.salary = salary;
    }

    @Id
    @Column(name = "EMPLOYEE_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "NAME")
    private String name;

    @Column(name = "SALARY")
    private double salary;

    @OneToOne(fetch = FetchType.LAZY)
   @PrimaryKeyJoinColumn
    private Address address;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public double getSalary() {
        return salary;
    }

    public Employee setSalary(double salary) {
        this.salary = salary;
        return this;
    }

    public Address getAddress() {
        return address;
    }

    public Employee setAddress(Address address) {
        this.address = address;
        return this;
    }

    @Override
    public String toString() {
        return "BiEmployee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salary=" + salary +
                ", address=" + address +
                '}';
    }
}

Address.java

@Entity
@Table(name = "ADDRESS")
public class Address implements Serializable {

    @Id
    @Column(name = "EMPLOYEE_ID")
    private int id;

    @Column(name = "STREET_NAME")
    private String streetName;

    @Column(name = "CITY_NAME")
    private String cityName;

    @Column(name = "STATE_NAME")
    private String stateName;

    @Column(name = "ZIP_CODE")
    private String zipCode;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "COUNTRY_CODE")
    private Country country;

    public int getId() {
        return id;
    }

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

    public String getStreetName() {
        return streetName;
    }

    public Address setStreetName(String streetName) {
        this.streetName = streetName;
        return this;
    }

    public String getCityName() {
        return cityName;
    }

    public Address setCityName(String cityName) {
        this.cityName = cityName;
        return this;
    }

    public String getStateName() {
        return stateName;
    }

    public Address setStateName(String stateName) {
        this.stateName = stateName;
        return this;
    }

    public String getZipCode() {
        return zipCode;
    }

    public Address setZipCode(String zipCode) {
        this.zipCode = zipCode;
        return this;
    }

    public Country getCountry() {
        return country;
    }

    public Address setCountry(Country country) {
        this.country = country;
        return this;
    }

    @Override
    public String toString() {
        return "BiAddress{" +
                "id=" + id +
                ", streetName='" + streetName + '\'' +
                ", cityName='" + cityName + '\'' +
                ", stateName='" + stateName + '\'' +
                ", zipCode='" + zipCode + '\'' +
                '}';
    }
}

添加Country.java以获得完整性

@Entity
@Table(name = "COUNTRY")
public class Country {

    @Id
    @Column(name = "COUNTRY_CODE")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int countryCode;

    @Column(name = "COUNTRY_NAME")
    private String name;

    public int getCountryCode() {
        return countryCode;
    }

    public Country setCountryCode(int countryCode) {
        this.countryCode = countryCode;
        return this;
    }

    public String getName() {
        return name;
    }

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