现在的位置: 首页 > 综合 > 正文

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

2018年01月26日 ⁄ 综合 ⁄ 共 1108字 ⁄ 字号 评论关闭

【联合主键】

>>>>配置方式: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>

 

抱歉!评论已关闭.