Return to site

๐Ÿƒโž•๐Ÿ”‘ SpringBoot and JPA composite key

ยท java

Sometimes you need to use several attributes of an entity to design your DB primary key.

JPA composite key serves that purpose.

Let's see how to implement such composite key !

 

 

1๏ธโƒฃ ๐˜๐จ๐ฎ ๐๐ž๐Ÿ๐ข๐ง๐ž ๐ญ๐ก๐ž ๐‚๐จ๐ฆ๐ฉ๐จ๐ฌ๐ข๐ญ๐ž ๐Š๐ž๐ฒ๐Ÿ”‘ ๐‚๐ฅ๐š๐ฌ๐ฌ ๐Ÿ๐จ๐ซ ๐ญ๐ก๐ž ๐ข๐:

public class ๐๐จ๐จ๐ค๐ˆ๐ implements Serializable {

  private String ๐š๐ฎ๐ญ๐ก๐จ๐ซ;
  private String ๐ง๐š๐ฆ๐ž;

  // standard getters and setters
}

 

 

2๏ธโƒฃ ๐˜๐จ๐ฎ ๐ฎ๐ฌ๐ž ๐ข๐ญ ๐š๐ฌ ๐ข๐๐Ÿ†” ๐ข๐ง ๐ฒ๐จ๐ฎ๐ซ ๐ž๐ง๐ญ๐ข๐ญ๐ฒ:

@Entity
public class Book {

  @๐„๐ฆ๐›๐ž๐๐๐ž๐๐ˆ๐
  private ๐๐จ๐จ๐ค๐ˆ๐ ๐ข๐;
  private String genre;
  private Integer price;

  //standard getters and setters
}

 

 

 

3๏ธโƒฃ ๐˜๐จ๐ฎ ๐Ÿ๐ข๐ง๐š๐ฅ๐ฅ๐ฒ ๐ฆ๐š๐ค๐ž ๐ฒ๐จ๐ฎ๐ซ ๐œ๐š๐ฅ๐ฅ๐ฌ๐Ÿ“ž ๐ญ๐จ ๐ญ๐ก๐ž ๐ซ๐ž๐ฉ๐จ๐ฌ๐ข๐ญ๐จ๐ซ๐ฒ:

@Repository
public interface BookRepository extends JpaRepository<Book, ๐๐จ๐จ๐ค๐ˆ๐> {

  List<Book> findById๐๐š๐ฆ๐ž(String name);

  List<Book> findById๐€๐ฎ๐ญ๐ก๐จ๐ซ(String author);
}