1. 数据库的表结构
CREATE TABLE `software` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `version` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`publish_time` datetime NOT NULL,
`software_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
);
2. java的class
---------------------------------------
Software.java
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.Entity;
@Entity
public class Software {
private Long id;
private String name;
private Set<Version> versions = new LinkedHashSet<Version>();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToMany(cascade = { CascadeType.ALL }, mappedBy="software")
@JoinColumn(name = "software_id")
@Fetch(FetchMode.SUBSELECT)
@OrderBy("id")
public Set<Version> getVersions() {
return version;
}
public void setVersions(Set<Version> Versions) {
this.versions = versions;
}
}
-----------------------------------------------------
Version.java
import java.util.Date;
import javax.persistence.Entity;
@Entity
public class Version{
private Long id;
private Date publishTime;
private Software software;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE })
@JoinColumn(name = "software_id")
public Software getSoftware() {
return software;
}
public void setSoftware(Software software) {
this.software = software;
}
}
3. 测试代码
Software software = new Software();
software.setName("Windows");
Version version = new Version;
version.setPublishTime(new Date());
version.setSoftware(software);
software.getVersions().add(version);
software.save();
hibernate会自动生成两条insert语句,一条是software的insert语句,一条是version的insert语句。
同样,如果删除software的话,也会生成两条delete语句