开发者

Can I create my own sequence in Hibernate?

Can I create my own sequence in Hibernate, like I开发者_如何学C have a database sequence and I have to add 2 characters before the sequence?


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;
}


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")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜