java - 我可以在 Hibernate 中创建自己的序列吗?

标签 java hibernate sequence

我可以在 Hibernate 中创建自己的序列吗? ,就像我有一个数据库序列,我必须在序列前添加 2 个字符?

最佳答案

您可以创建自己的标识符生成器。看看这个blog post这基本上展示了如何做类似于你正在寻找的事情(除非我误解了这个问题):

Custom Hibernate Sequence Generator for Id field

I have a table with a primary key in the format M001, M002 etc (lets not think about what happens after M999 for now). I’m using Hibernate Annotations, and I found a great way of generating the Primary Key value for new Records:

First I created a database sequence to use. Then I implemented org.hibernate.id.IdentifierGenerator;

public class StockCodeGenerator implements IdentifierGenerator {

    private static Logger log = Logger.getLogger(StockCodeGenerator.class);

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

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

            PreparedStatement ps = connection
                    .prepareStatement("SELECT nextval ('seq_stock_code') as nextval");

            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("nextval");
                String code = prefix + StringUtils.leftPad("" + id,3, '0');
                log.debug("Generated Stock Code: " + code);
                return code;
            }

        } catch (SQLException e) {
            log.error(e);
            throw new HibernateException(
                    "Unable to generate Stock Code Sequence");
        }
        return null;
    }
}

Then, in my entity class, I simply annotate the id field like this:

@Id
@GenericGenerator(name="seq_id", strategy="my.package.StockCodeGenerator")
@GeneratedValue(generator="seq_id")
@Column(name = "stock_code", unique = true, nullable = false, length = 20)
public String getStockCode() {
    return this.stockCode;
}

关于java - 我可以在 Hibernate 中创建自己的序列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3649652/

相关文章:

java - redis 集合成员更新的高效方式

java - 如何在Spring中从序列生成实体字段的部分值?

javascript - 来自较早 promise 的控制台日志出现在来自最新 promise 的控制台日志之后

java - 使用 Jsoup 检索时间标签

java - asm如何生成子类

java - 在电话上运行 tess-two

java - Hibernate 模板翻译

java - 如何使用 ids 插入记录列表?

java - hibernate/C3P0 : Server crashes after MySQL timeout

python - 如何在Python中实现动态序列(例如 "geometric range")?