比對相同資料寫法
有一筆pojo資料,要查出與他相同的其他資料
POJO
@Entity @Table(name = "RECEIVER") public class ReceiverDTO implements Serializable { private static final long serialVersionUID = -5368343800218280407L; @Id private String id; @Column private String name; @Column private String email; @Column private String mobile; @Column private String phone; @Temporal(TemporalType.TIMESTAMP) @Column private Date updateTime; public MemReceiverDTO() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
hibernate
public List<ReceiverDTO> findSameData(ReceiverDTO DTO) { //搜尋資料以Map包裝 Map map = new HashMap(); map.put("name",DTO.getName()); map.put("mobile",DTO.getMobile()); map.put("email",DTO.getEmail()); Criteria criteria = this.getSession().createCriteria(ReceiverDTO.class); criteria.add(Restrictions.allEq(map)); //下條件 criteria.addOrder(Order.desc("updateTime")); return criteria.list(); }
Spring Data JPA
利用 .findAll(Example<T> example) public List<ReceiverDTO> findSameData(ReceiverDTO DTO) { //建立ExampleMatcher規則 //withIgnorePaths 不加入比對的data //withIncludeNullValues 不要略過null的path (如果 path = null 也要比對) ExampleMatcher exampleMatcher = ExampleMatcher.matching().withIgnorePaths("id", "phone", "updateTime").withIncludeNullValues(); //use spring data jpa : .findAll(Example<T> example, Sort sort) List<ReceiverDTO> sameDataList = receiverRepository.findAll(Example.of(DTO, exampleMatcher), new Sort(Sort.Direction.DESC, "updateTime")); }
文章標籤
全站熱搜