hibernate3.6-联合主键注解以及openSession和getCurrentSession区别

本文介绍了在Hibernate中配置联合主键的两种方法,包括XML配置和注解方式,并对比了openSession与getCurrentSession的区别,帮助理解不同场景下的Session使用。

【联合主键】

>>>>配置方式:xml:
    1. Student中单独创建StudentPk主键实体类

    2. 配置:

<composite-id name="studentPK"> 
    <key-property name="name" column="username" /> 
    <key-property name="nickname" column="nickname" /> 
</composite-id>

>>>>注解方式:annotation

     1. Teacher中单独创建TeacherPk主键实体类

     2.注解
        ** 注解方式1:【一个注解】※常用

        <1>

@EmbeddedId
public TeacherPk getTeacherPk()

        <2>主键类实现Serializable接口+重写hashCode和equals方法。         

 

TeacherPk implements Serializable{

    @Override
    public int hashCode()

    @Override
    public boolean equals(Object obj)
}

    **注解方式2:【两个注解】

        <1> 

@Embeddable
public class TeacherPk implements Serializable

 

@Id
public TeacherPk getTeacherPk()

        <2>同上

 【openSession和getCurrentSession区别】

1.    openSession产生的实例是SessionImpl.class的实例;
    getCurrentSession产生的是$Proxy代理类实例

2.    openSession每次调用产生新的Session;
    getCurrentSession在第一次调用时生成新的Session,之后关联到上下文,
    在事务完成(commit/rollback)之前,每次得到的都是已经存在的Session,
    直到事务提交或者回滚。

3.    openSession的Session需要手动close();
    getCurrentSession的会在事务完成(commit/rollback)时自动close。

4.    openSession的可以直接使用。
    getCurrentSession需要再hibernate的配置文件中配置current_session_context_class.。比如:
    

<property name="current_session_context_class">thread</property>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值