JPA: How to get entity based on field value other than ID?

前端 未结 15 948
时光说笑
时光说笑 2020-12-04 21:08

In JPA (Hibernate), when we automatically generate the ID field, it is assumed that the user has no knowledge about this key. So, when obtaining the entity, user would query

15条回答
  •  星月不相逢
    2020-12-04 21:33

    I solved a similar problem, where I wanted to find a book by its isbnCode not by your id(primary key).

    @Entity
    public class Book implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Integer id;
        private String isbnCode;
    
    ...
    

    In the repository the method was created like @kamalveer singh mentioned. Note that the method name is findBy+fieldName (in my case: findByisbnCode):

    @Repository
    public interface BookRepository extends JpaRepository {
    
        Book findByisbnCode(String isbnCode);
    }
    

    Then, implemented the method in the service:

    @Service
    public class BookService {
    
        @Autowired
        private BookRepository repo;
        
        
        public Book findByIsbnCode(String isbnCode) {
            Book obj = repo.findByisbnCode(isbnCode);
            return obj; 
        }
    }
    

提交回复
热议问题