您的位置:首页 > 其它

hibernate学习:映射之主键

2015-03-05 00:01 369 查看
给实体类添加标示符属性

public class Category{
private Long id;
public Long getId(){
return this.id;
}
private void setId(Long id){  //hibernate生成时自动设置,保证id的唯一性,不可变性
this.id = id;
}
}
hibernate xml配置标示符属性

<pre name="code" class="html"><span style="font-family: Arial, Helvetica, sans-serif;"><class name="category" table="CATEGORY"></span>
<id name="id" column="CATEGORY_ID" type="long">
<span>	</span><generator class="native"/>
</id>
...
</pre><pre name="code" class="html"></class>



JPA/hibernate注解方式配置标示符属性

@Entity
@table(name="CATEGORY")
public class Category
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="CATEGORY_ID")   //不指定时,使用属性名称作为数据库列名
public Long getId(){
return this.id;
}
private void setId(Long id){
this.id = id;
}
}


当@Id注解在字段上时,hibernate访问此类的所有属性皆通过字段访问。

当@Id注解在get方法上时,hibernate访问此类则通过get方法。

hibernate的 @AccessType注解可以选择访问方式,可以注解在类上,访问方法上,字段上。提供了比@Id这种隐式的方式更为细粒度的控制

主键的选择:

1,永远不会为空

2,每一行都有唯一的值

3,一个特定行的值永远不变

常用主键生成策略

Hibernate类型JPA类型选项描述
nativeAUTO--此生成器将根据底层数据库的不同自动挑选不同的其他生成器
identityIDENTITY--支持DB2,MySQL, SQL SERVER,返回类型为long short 或 int
sequenceSEQUENCEsequence,parameter支持DB2,ORACLE 返回类型为long short 或 int
increment不可用-- 由hibernate自动生成,每次增加1
@Entity
@org.hibernate.annotations.GenericGenerator(
name = "hiberate-uuid",
strategy = "uuid"
)
class MyEntity{
@Id
@Column(name="MY_ID")
@GeneratedValue(generator = "hibernate-uuid")
String id;
}


在xml中声明一个具名MY_SEQUENCE的数据库序列         全局序列生成器

<sequence-generator name="mySequenceGenerator" sequence-name="MY_SEQUENCE" initial-value="123" allocation-size="20"/>
在注解中使用它

@Entity
class MyEntity{
@Id @GeneratedValue(generator="mySequenceGenerator")
String id;
}
如果在实体类中生命一个同名的生成器,且在class关键字之前,则它会覆盖全局生成器

@TableGenerator 表生成id方式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate 主键映射
相关文章推荐