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
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