JPA or Hibernate to generate a (non primary key) column value, not starting from 1

前端 未结 3 1172
别跟我提以往
别跟我提以往 2021-01-06 06:10

I want a JPA/Hibernate (preferably JPA) annotation that can generate the value of a column, that is not a primary key and it doesn\'t start from 1.

From what I have

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 07:03

    Related to @Vlad Mihalcea, now you can use @GeneratorType to generate your own custom value for non id column. For example:

    1. Entity:
        import org.hibernate.annotations.GeneratorType
    
        @GeneratorType(type = CustomGenerator.class, when = GenerationTime.INSERT)
        @Column(name = "CUSTOM_COLUMN", unique = true, nullable = false, updatable = false, lenght = 64)
        private String custom;
    
    1. ValueGenerator implementation:
    public class CustomGenerator extends ValueGenerator {
            private static final String TODAY_EXAMPLE_QUERY = "from Example where createDate>:start and createDate<:end order by createDate desc";
            private static final String START_PARAMETER = "start";
            private static final String END_PARAMETER = "end";
            private static final String NEXTVAL_QUERY = "select EXAMPLE_SEQ.nextval from dual";
            private final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd");
    
            @Override
            public String generateValue(Session session, Object owner) {
                Date now = new Date();
                Query todayQuery = session.createQuery(TODAY_EXAMPLE_QUERY, Example.class);
                query.setParameter(START_PARAMETER, start(now));
                query.setParameter(END_PARAMETER, end(now));
                Example lastExample = todayQuery.setMaxResult(1).setHibernateFlushMode(COMMIT).uniqueResult();
    
                NativeQuery nextvalQuery = session.createSQLQuery(NEXTVAL_QUERY);
                Number nextvalValue = nextvalQuery.setFlushMode(COMMIT).uniqueResult();
                return dataFormat.format(now) + someParameter(lastExample) + nextvalValue.longValue();
            }
        }
    

提交回复
热议问题