Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 853
membersound Avatar asked Apr 10 '15 12:04

membersound


People also ask

Can I have 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.

Can we use JPA repository without primary key?

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.

Why id is mandatory in JPA?

Id is required by JPA, but it is not required that the Id specified in your mapping match the Id in your database. For instance you can map a table with no id to a jpa entity. To do it just specify that the "Jpa Id" is the combination of all columns.

Is @repository annotation mandatory?

It is indeed not necessary to put the @Repository annotation on interfaces that extend JpaRepository ; Spring recognises the repositories by the fact that they extend one of the predefined Repository interfaces.


2 Answers

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

like image 131
Sergey Pauk Avatar answered Sep 22 '22 09:09

Sergey Pauk


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

like image 35
sourabhteke Avatar answered Sep 18 '22 09:09

sourabhteke