why when a repository is created
public interface BookRepository extends JpaRepository<Book,Long> {
which means <Book,Long>
, what is it for or what?
why when a repository is created
public interface BookRepository extends JpaRepository<Book,Long> {
which means <Book,Long>
, what is it for or what?
Book is the entity that represents the table in your database.
Example:
@Entity()
@Table(name="name_table")
public class NameTableEntity {
//fields
}
It should be noted that the Repository can be created by annotation, to avoid configuration by XML:
@Repository
public interface BookRepository extends JpaRepository<Book,Long> {
//methods
}
The repository is an interface and extends the JpaRepository interface that contains generics, the first one is the class of the entity and the second one is the identifier class (Id)
Example 1:
@Entity()
@Table(name="name_table")
public class NameTableEntity {
@Id
long id;
}
The repository would be:
@Repository
public interface NameTableRepository extends JpaRepository<NameTableEntity,Long> {
//methods
}
Example 2:
@Entity()
@Table(name="name_table")
public class NameTableEntity {
@Id
String id;
}
The repository would be:
@Repository
public interface NameTableRepository extends JpaRepository<NameTableEntity,String> {
//methods
}
For what purpose? Well, the JpaRepository interface contains defined methods to save, search and delete, some for example:
List<T> findAll();
<S extends T> List<S> save(Iterable<S> entities);
<S extends T> S findOne(Example<S> example);
example 1:
List<NameTableEntity> findAll();
NameTableEntity save(NameTableEntity nameTableEntity);
NameTableEntity findOne(Long id);
example 2:
List<NameTableEntity> findAll();
NameTableEntity save(NameTableEntity nameTableEntity);
NameTableEntity findOne(String id);
JpaRepository at the end extends from CrudRepository, but at a lower level, which will facilitate almost all the work with JPA functions since the methods find, save, delete, update, findbyid etc. are implemented transparently for you.
That is why you have to define JpaRepository<Book,Long>
where long is the data type of the primary key of the entity and Book is the entity itself that will be used to autogenerate the functions that I mentioned earlier.
Greetings.