我需要将主表的主键转发到依赖表中的外键字段

时间:2011-09-21 16:07:58

标签: hibernate spring jpa hibernate-mapping hibernate-annotations

我有2个实体客户和地址请找到下面的代码,为简单起见,我省略了锅炉板代码。

public class Customer  implements java.io.Serializable {
  private static final long serialVersionUID = 3116894694769321104L;
     private short customerId;
     private Address address;
     private String firstName;
     private String lastName;
     private String email;
     private boolean active;
     private Date createDate;
     private Date lastUpdate;


    // Property accessors
    @Id
    @Column(name="customer_id", unique=true, nullable=false, insertable=true, updatable=true)

    public short getCustomerId() {
        return this.customerId;
    }

    public void setCustomerId(short customerId) {
        this.customerId = customerId;
    }
    @ManyToOne(cascade={CascadeType.ALL},
        fetch=FetchType.LAZY)

        @JoinColumn(name="address_id", unique=false, nullable=false, insertable=true, updatable=true)

    public Address getAddress() {
        return this.address;
    }

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

和地址类是:

public class Address  implements java.io.Serializable {


    // Fields    

     private short addressId;
     private short customerId;
     private String address;
     private String address2;
     private String district;
     private String postalCode;
     private String phone;
     private Date lastUpdate;
     private Set<Customer> customers_1 = new HashSet<Customer>(0);


    // Constructors

    /** default constructor */
    public Address() {
    }

   // Property accessors
    @Id
    @Column(name="address_id", unique=true, nullable=false, insertable=true, updatable=true)

    public short getAddressId() {
        return this.addressId;
    }

    public void setAddressId(short addressId) {
        this.addressId = addressId;
    }

    /**
     * ??????what goes here
     */
    public short getCustomerId() {
        return customerId;
    }

    /**
     * @param customerId the customerId to set
     */
    public void setCustomerId(short customerId) {
        this.customerId = customerId;
    }

我需要将客户ID作为外键保存在地址表中。

1 个答案:

答案 0 :(得分:1)

只需与Customer使用@ManyToOne关系即可。因此,代替Java代码中的customerId,您将使用Customer对象进行操作,但在数据库级别,Hibernate将使用外键与客户进行表格。