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

发布于 2024-09-17 15:28:25 字数 152 浏览 2 评论 0原文

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

Can I create my own sequence in Hibernate, like I have a database sequence and I have to add 2 characters before the sequence?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寻找一个思念的角度 2024-09-24 15:29:06

试试这个。使用 Date 和 Calender

 public class StockCodeGenerator
 implements IdentifierGenerator
 {
 private static Logger log = Logger.getLogger(StockCodeGenerator.class);


 public StockCodeGenerator() {}

 public int generateCustId()
 {
 Random random = new Random();
 return random.nextInt(100);
 }


 public Serializable generate(SessionImplementor session, Object object)
 throws HibernateException
 {
 String prefix = "Custom_String";
 Connection connection = session.connection();
 System.out.println(session.connection());


 Date date = new Date();

 Calendar calendar = Calendar.getInstance();
 return prefix + "_" + generateCustId() + "_" + calendar.get(1);
 }
 }

然后在 @GenericGenerator 注释中使用它

@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")

Try this one. With Date and Calender

 public class StockCodeGenerator
 implements IdentifierGenerator
 {
 private static Logger log = Logger.getLogger(StockCodeGenerator.class);


 public StockCodeGenerator() {}

 public int generateCustId()
 {
 Random random = new Random();
 return random.nextInt(100);
 }


 public Serializable generate(SessionImplementor session, Object object)
 throws HibernateException
 {
 String prefix = "Custom_String";
 Connection connection = session.connection();
 System.out.println(session.connection());


 Date date = new Date();

 Calendar calendar = Calendar.getInstance();
 return prefix + "_" + generateCustId() + "_" + calendar.get(1);
 }
 }

And then use it in your @GenericGenerator annotation

@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")
奶茶白久 2024-09-24 15:28:56

您可以创建自己的标识符生成器。看看这篇博客文章,它基本上展示了如何做类似的事情你在寻找什么(除非我误解了这个问题):

Id 字段的自定义 Hibernate 序列生成器

我有一个带有主键的表
格式 M001、M002 等(让我们不要
想想M999之后会发生什么
目前)。我正在使用休眠
注释,我发现了一个很好的方法
生成主键值
对于新记录:

首先我创建了一个数据库序列
使用。然后我实施了
org.hibernate.id.IdentifierGenerator;

公共类 StockCodeGenerator 实现 IdentifierGenerator {

    私有静态 Logger 日志 = Logger.getLogger(StockCodeGenerator.class);

    公共可序列化生成(SessionImplementor会话,Object对象)
            抛出 HibernateException {

        字符串前缀=“M”;
        连接连接 = session.connection();
        尝试 {

            准备好的语句 ps = 连接
                    .prepareStatement("SELECT nextval('seq_stock_code') as nextval");

            结果集 rs = ps.executeQuery();
            如果 (rs.next()) {
                int id = rs.getInt("nextval");
                字符串代码 = prefix + StringUtils.leftPad("" + id,3, '0');
                log.debug("生成的股票代码:" + code);
                返回码;
            }

        } catch (SQLException e) {
            日志错误(e);
            抛出新的 HibernateException(
                    “无法生成股票代码序列”);
        }
        返回空值;
    }
}

然后,在我的实体类中,我只需
像这样注释 id 字段:

<前><代码>@Id
@GenericGenerator(名称=“seq_id”,策略=“my.package.StockCodeGenerator”)
@GenerateValue(生成器=“seq_id”)
@Column(name = "stock_code", unique = true, nullable = false, length = 20)
公共字符串 getStockCode() {
返回 this.stockCode;
}

You can create your own identifier generator. Have a look at this blog post which is basically showing how to do something similar to what you're looking for (unless I misundertsood the question):

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文