Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Usage of @GeneratedValue on non-id column

Tags:

jpa

I am attempting to persist an entity with an attribute that I want to be populated from a DB sequence. I'm using Oracle, have created the sequence, verified the sequence works via sql, and yet my attribute isn't getting populated. Here's what I have:

@GeneratedValue(generator = "RFQ_LINE_IDS_SEQUENCE", strategy=GenerationType.SEQUENCE)
@SequenceGenerator(name="RFQ_LINE_IDS_SEQUENCE", sequenceName="RFQ_LINE_IDS_SEQUENCE", allocationSize=1000000000)
@Column(name = "external_line_item_id")
private String externalLineItemId;

All the examples I'm seen online show this annotation being used with @Id, but I have another attribute that I'm using for my id.

I've also tried the following to no avail:

@GeneratedValue(generator = "RFQ_LINE_IDS_SEQUENCE", strategy=GenerationType.SEQUENCE)
@GenericGenerator(name = "RFQ_LINE_IDS_SEQUENCE", strategy = "sequence",
  parameters = {@Parameter(name = "sequence", value = "RFQ_LINE_IDS_SEQUENCE")})
@Column(name = "external_line_item_id")
private String externalLineItemId;
like image 989
fmpdmb Avatar asked Mar 06 '13 16:03

fmpdmb


People also ask

Can we use JPA without primary key?

There are a number of different ways you can handle it but it really is situational. If your table without a key has a foreign key into another table that does have an id, you can use the @Embedded annotation.

Can @generatevalue be used with non primary key attributes?

As per documentation as well as hibernate documentation though this annotation is specifically aimed for simple primary keys (as its elements are used to define primary key generator & strategy), I think you can still use this for non-primary key field provided you are not using any elements of this annotation.

What is the use of @GeneratedValue annotation?

Annotation Type GeneratedValueProvides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.

Can we create JPA entity without @ID?

If your object does not have an id, but its' table does, this is fine. Make the object an Embeddable object, embeddable objects do not have ids. You will need a Entity that contains this Embeddable to persist and query it. Show activity on this post.


1 Answers

JPA only mandates support for @GeneratedValue on @Id fields. Some JPA implementations (such as DataNucleus JPA) support it but not all do.

like image 101
DataNucleus Avatar answered Oct 01 '22 05:10

DataNucleus