Reputation: 86777
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
Reputation: 10920
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;
}
interface MyEntityRepo extends CrudRepository<MyEntity, MyEntity> {
// ^^^the full record is the ID
See also:
Upvotes: 5
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
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