Yash
Yash

Reputation: 1018

Saving an entity without fetching ID

I have a table T1(ID AUTOINCREMENT INT, COL1, COL2, etc).

The JPA Entity for T1 has a field ID which has been marked as @Generated and @Id. This is to tell JPA that the key of the entity is not set by the application and that the DB will be generating the ID. The code invokes the persist method to save the entity. I do not need the entity to be managed.

@Entity
@Table(name = "T1")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "ID")
    private Long customerd;
    @Column(name = "COL1")
    private String col1;

When I run the application, JPA seems to INSERT the row in the table and immediately SELECT the generated ID to be set in the object.

Is it possible to tell JPA not to fetch the generated ID? I want JPA to perform the INSERT and forget the record.

The database is DB2. The JPA implementation is Hibernate.

Regards,

Yash

Upvotes: 0

Views: 1144

Answers (1)

Ish
Ish

Reputation: 4154

Per JPA Spec, every entity must have a primary key - can be simple or composite primary key. That means you have to specify at least a property to indicate it is the primary key of your entity by using @Id or @EmbeddedId annotations. JPA provider will ensure that the entity's generated id will be available in the Id annotated property during the persist call. The JPA provider will assign the Id either before or after the transaction has committed (depends of the generation strategy used). Regardless of strategy used and unless you manually set the Id property yourself, that won't prevent the JPA provider from querying the generated Id and assigning it to your Entity.

Upvotes: 1

Related Questions