I have to say, JPA 2.0 is pretty awesome – it does a great job of Entity Relation mapping. Overall I really like the ORM framework and I’m glad its built into Java now. However, its by far not a perfect solution to all database related tasks. For example, some of the generated SQL isn’t the best. But that can easily be solved by writing your own SQL using NamedQueries.
Another common task is to generate records with primary keys that are sequenced based. This is easily accomplished by using the @GeneratedValue tag and a @SequenceGenerator
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SeqGen") @SequenceGenerator(name = "SeqGen", sequenceName = "SAMPLE_SEQUENCE", allocationSize = 1)
But what if you wanted to generate a value that is based off a Sequence? You don’t want to tie this value to a Primary Key, instead maybe you want to populate another field with it? Or generate a confirmation id, etc.
As far as I know, there is no annotation that will query a Sequence and simply return its value. I ended up using a query to return the next Sequence value:
Query q = em.createNativeQuery("SELECT SAMPLE_SEQUENCE.nextval from DUAL"); BigDecimal result=(BigDecimal)q.getSingleResult(); return result.longValue();
Anyone know of a better way to accomplish this?