【问题标题】:I need to carry forward the primary table's primary key to a foreign key field in dependent table我需要将主表的主键结转到从属表中的外键字段
【发布时间】:2011-11-22 02:44:46
【问题描述】:

我有 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 作为外键保存在地址表中。

【问题讨论】:

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


    【解决方案1】:

    只需使用@ManyToOneCustomer 的关系。因此,您将使用 Customer 对象而不是 Java 代码中的 customerId,但在数据库级别,Hibernate 将使用外键与客户表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多