I need to carry forward the primary table's primary key to a foreign key field in dependent table
I have 2 entities Customer and address please find the code below, I have omitted boiler plate code for simplicity.
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) {
t开发者_StackOverflow社区his.address = address;
}
and Address class is :
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;
}
I need to persist the customer id as a foreign key in address table.
Just use @ManyToOne
relationship with Customer
. So, instead of customerId
in Java code you will be operates with Customer
object, but at database level Hibernate will use foreign key to table with customer.
精彩评论