membersound
membersound

Reputation: 86777

How to use spring Repository without @Id?

I'm using spring CrudRepository throughout my application. Now I want to also create one for an @Entity that does not have an @Id. Is that possible at all?

//probably ID is always required?
public interface Repository<T, ID extends Serializable>

Upvotes: 43

Views: 103266

Answers (3)

epox
epox

Reputation: 10920

Use @IdClass (composite key)

Yes, this is possible. This approach can be used when you read from a DB view. The below example demonstrates how to mark all (2, in the given example) columns as the composite ID:

import java.io.Serializable;
import lombok.Data;          // auto-generates  AllArgs contractor, getters/setters, equals, and hashcode 

@Data
@Entity
@IdClass(MyEntity.class)                         // <--this is the extra annotation to add
@Table(name = "my_table")
public class MyEntity implements Serializable{   // <--this is the extra interface to add
  @Id                                            // annotate each column with @Id
  private String column1;

  @Id                                            // annotate each column with @Id
  private String column2;
}
  • The above MyEntity uses the full record state as the key:
  • --so, in addition to @EqualsAndHashcode, do flag the class with Serializable interface;
  • --annotate each field with @ID
  • In your <T, ID> repository say the ID is your full (entity) class:

interface MyEntityRepo extends CrudRepository<MyEntity, MyEntity> {
                                                        // ^^^the full record is the ID

See also:

  1. docs.oracle.com - Example 7.4-7.5: Non-Embedded Composite Primary Key
  2. baeldung.com/jpa-composite-primary-keys, for more fine-grained custom IdClass, with fewer (than all) columns in the ID.

Upvotes: 5

sourabhteke
sourabhteke

Reputation: 39

Alternatively you can extend AbstractPersistable<Long> for your all POJO entities.

Follow example: - https://github.com/spring-projects/spring-data-examples/blob/master/jpa/example/src/main/java/example/springdata/jpa/simple/User.java

Upvotes: 2

S. Pauk
S. Pauk

Reputation: 5318

JPA requires that every entity has an ID. So no, entity w/o an ID is not allowed.

Every JPA entity must have a primary key.

from JPA spec

You may want to read more about how JPA handles a case when there's no id on the DB side from here (see 'No Primary Key').

Upvotes: 43

Related Questions