3:数据库序列Sequence
像Oracle这种数据库支持序列生成主键的策略,那么就可以使用JPA的Sequence作为主键的生成策略。代码如下:
@Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.SEQUENCE) public Integer getId() { return id; } |
MySql暂时不支持序列这种主键策略,所以遇到MySql这种数据库的时候,不能使用SEQUENCE主键策略。
4:Identity生成器
有些数据库支持Identity字段作为生成器,MS SQL支持,主键创建Identity,实体标注如下:
@Id @Column(name = "id") @GeneratedValue(strategy=GenerationType.IDENTITY) public Integer getId() { return id; } |
单字段主键的问题,我们暂时先讨论这里,下面我们一起看看复合主键。
表结构如下图所示:
根据这个表对应生成的实体对下代码如下:
package eo;
import javax.persistence.Column; import javax.persistence.Embeddable;
/** * TbStudentsId entity. @author MyEclipse Persistence Tools */ @Embeddable public class TbStudentsId implements java.io.Serializable {
// Fields
private String name; private String no;
// Constructors
/** default constructor */ public TbStudentsId() { }
/** full constructor */ public TbStudentsId(String name, String no) { this.name = name; this.no = no; }
// Property accessors
@Column(name = "name", nullable = false) public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
@Column(name = "no", nullable = false) public String getNo() { return this.no; }
public void setNo(String no) { this.no = no; }
public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof TbStudentsId)) return false; TbStudentsId castOther = (TbStudentsId) other;
return ((this.getName() == castOther.getName()) || (this.getName() != null && castOther.getName() != null && this.getName().equals( castOther.getName()))) && ((this.getNo() == castOther.getNo()) || (this.getNo() != null && castOther.getNo() != null && this.getNo().equals( castOther.getNo()))); }
public int hashCode() { int result = 17;
result = 37 * result + (getName() == null ? 0 : this.getName().hashCode()); result = 37 * result + (getNo() == null ? 0 : this.getNo().hashCode()); return result; } } |