JPA - FindByExample

前端 未结 7 1994
故里飘歌
故里飘歌 2020-12-08 04:29

Does anyone have a good example for how to do a findByExample in JPA that will work within a generic DAO via reflection for any entity type? I know I can do it via my prov

7条回答
  •  粉色の甜心
    2020-12-08 05:14

    you can use this https://github.com/xiaod0510/jpa-findbyexample

    if your entity is Contact:

    @Entity
    public class Contact {
        @Id
        @GeneratedValue
        private Long id;
        @Column
        private String name;
        @Column
        private Date birthday;
        //Getter and Setter
    }
    public interface ContactRepository
            extends
            JpaSpecificationExecutor {
    }
    

    just create your own Example like this:

    public class ContactExample extends BaseExample {
        public final Attr id = new Attr("id");
        public final Attr name = new Attr("name");
        public final Attr birthday = new Attr("birthday");
        //default builder  
        public static ContactExample where() {
            ContactExample example = new ContactExample();
            example.operatorType = OperatorType.and;
            return example;
        }
    }
    

    and now you can query by example :

     ContactRepository.findOne(ContactExample
                        .where()//default is and
                        .id.eq(1l)
    );
    

    the example implements the interface "Specification",more information on that github

提交回复
热议问题