以Good和GoodStatus为例:
一、注解仅添加在一方:
@Entity
@Table(name = "GOOD")
@Where(clause="enabled=1") //Used for logical delete, disabled objects are always hidden
public class Good extends AMfgObject implements Serializable {
/** serialVersionUID */
private static final long serialVersionUID = -7656499731749432022L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "GOOD_ID", nullable = false)
private Long id;
@OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private Set<GoodStatus> goodStatus;
/**
* Empty constructor
*/
public Good(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<GoodStatus> getGoodStatus() {
return goodStatus;
}
public void setGoodStatus(Set<GoodStatus> goodStatus) {
this.goodStatus = goodStatus;
}
/**
* add GoodStatus directly
* @param goodStatus
*/
public void addGoodStatus(GoodStatus goodStatus){
this.goodStatus.add(goodStatus);
/*goodStatus.setGood(this);*/ //如果在多方也有注解则需添加这句,否则不能级联保存更新
}
}
在多方不加一方的映射(即不加Good good;这个属性)
@Entity
@Table(name = "GOODSTATUS")
@Where(clause = "enabled=1")
public class GoodStatus extends AMfgObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1279190303132720639L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private Long id;
@Column(name = "VALUE")
private String value;
public GoodStatus() {
super();
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
这种情况下生成的SQL语句是这样的:
CREATE TABLE good (
good_id bigint(20) NOT NULL auto_increment,
PRIMARY KEY (good_id)
) ;
-- create table goodstatus
CREATE TABLE goodstatus (
id bigint(20) NOT NULL AUTO_INCREMENT,
value varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (ID)
);
--good_good_status
CREATE TABLE good_good_status (
good_GOOD_ID bigint(20) NOT NULL,
good_status_id bigint(20) NOT NULL,
PRIMARY KEY (good_GOOD_ID,good_status_id),
KEY FK_GOOD_ID (good_GOOD_ID),
KEY FK_GOOD_STATUS_ID (good_status_id)
);
生成了三个表,类似于manytomany
二、注解仅添加在多的一方,则与双方都添加注解相同,仅生成两个表:
Good对应表不变,GoodStatus表
SQL语句对应如下:
-- create table goodstatus
CREATE TABLE goodstatus (
id bigint(20) NOT NULL AUTO_INCREMENT,
value varchar(255) COLLATE utf8_unicode_ci NOT NULL,
good_id bigint(20) DEFAULT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_GOOD_ID FOREIGN KEY (good_id) REFERENCES GOOD(ID)
);