10

我想使用注释指定以下 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注释下只指定类名吗?

4

2 回答 2

20

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

@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)
    {
        ...
    }
}
于 2012-07-24T13:39:34.973 回答
15

请参考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(value) as value from hibernate_tutorial.pk_table");

        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            int id = rs.getInt("value");
            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(value) as value from hibernate_tutorial.pk_table将从表 pk_table 中获取 MAX 数。然后我们在MAX数字前加上字符串“ EMP ”。

输出如下所示:

员工

------------------------------------------------------------
employee_id | birth_date | cell_phone | firstname | lastname
------------------------------------------------------------
EMP1        | 2014-08-22 | 111        | Nina      |  Mayers
于 2014-08-22T03:01:19.663 回答