Hibernate:如何使用注释指定自定义序列生成器类名?

时间:2012-07-24 13:22:22

标签: hibernate jpa

我想使用注释指定以下hbm配置:

<id name="somePK" column="&quot;somePK&quot;" type="long">
            <generator class="com.db.hibernate.KeyGenerator"/>
        </id>

我不确定如何使用

提供班级名称
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")

我是否必须在每个实体类中指定@javax.persistence.SequenceGenerator
我可以只在@GeneratedValue注释下指定类名吗?

2 个答案:

答案 0 :(得分:19)

请找到我在项目中使用的以下代码集。

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
        strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
        parameters = {
            @Parameter(name = "sequence", value = "xyz_id_sequence")
        })
public BigInteger getId()
{
   return id;
}


package com.mycompany.myapp.id;

import org.hibernate.id.SequenceGenerator;
...

public class BigIntegerSequenceGenerator
    extends SequenceGenerator
{
    @Override
    public Serializable generate(SessionImplementor session, Object obj)
    {
        ...
    }
}

答案 1 :(得分:13)

请参考custom-id-generator-in-hibernate这可能会对您有所帮助。 在这个例子中,我通过从名为 pk_table 的主键表中取MAX号来创建序列号。

员工类如下所示。

@Entity
@Table(name="EMPLOYEE")
public class Employee {

@Id
@GenericGenerator(name = "sequence_emp_id", strategy = "com.supportmycode.model.EmployeeIdGenerator")
@GeneratedValue(generator = "sequence_emp_id")  
@Column(name="employee_id")
private String employeeId;

@Column(name="firstname")
private String firstname;

@Column(name="lastname")
private String lastname;

@Column(name="birth_date")
private Date birthDate;

@Column(name="cell_phone")
private String cellphone;

//Getter and Setter methods.
}

EmployeeIdGenerator 类如下所示

public class EmployeeIdGenerator implements IdentifierGenerator {

public Serializable generate(SessionImplementor session, Object object)
        throws HibernateException {

    String prefix = "EMP";
    Connection connection = session.connection();
    try {

        PreparedStatement ps = connection
                .prepareStatement("SELECT MAX(vlaue) as vlaue from hibernate_tutorial.pk_table");

        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            int id = rs.getInt("vlaue");
            String code = prefix + new Integer(id).toString();
            System.out.println("Generated Stock Code: " + code);
            return code;
        }

    } catch (SQLException e) {       
        e.printStackTrace();
    }
    return null;
}

}

在这里,我们已经实现了接口 IdentifierGenerator 来覆盖函数 generate(SessionImplementor session,Object object)。语句 SELECT MAX(vlaue)作为来自hibernate_tutorial.pk_table 的值,将从表pk_table中获取MAX号。然后我们在 MAX 数字前加上字符串&#34; EMP &#34;。

输出如下:

EMPLOYEE

employee_id | birth_date | cell_phone |名字|名字

EMP1 | 2014-08-22 | 111 |妮娜|迈耶斯