39

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>
S. Pauk
  • 5,208
  • 4
  • 31
  • 41
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

41

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').

S. Pauk
  • 5,208
  • 4
  • 31
  • 41
3

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.
epox
  • 9,236
  • 1
  • 55
  • 38
2

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

sourabhteke
  • 39
  • 1
  • 5