hibernate学习:映射之主键

给实体类添加标示符属性

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方式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值