如何使用规范将spring-data-jpa中的where条件与表连接起来?

时间:2017-03-16 15:22:56

标签: spring-data spring-data-jpa

作为问题的标题,我如何使用规范将spring-data-jpa中的where条件与表连接起来。你可以帮助我吗?

People.java

@Entity
@Table(name = "people")
public class People {

    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private Integer people_id;
    @Column
    private Integer peopleAge;    
    with getters and setters...
}

Home.java

@Entity
@Table(name = "home")
public class Home{

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private Integer homeId;
@Column
private String homeName;
@Column
private String peopleId;
 with the getter and setter ..}

PeopleRepository.java

public interface PeopleRepository extends JpaRepository<People, Integer>, JpaSpecificationExecutor<People> {
}

PeopleSpecification.java

public class PeopleSpecification implements Specification<People> {
    private SearchCriteria criteria;

    public PeopleSpecification(SearchCriteria criteria) {
        this.criteria = criteria;
    }

    @Override
    public Predicate toPredicate(Root<People> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder builder) {
        if (criteria.getOperation().equalsIgnoreCase("==")) {
            return builder.greaterThanOrEqualTo(
                    root.<String> get(criteria.getKey()), criteria.getValue().toString());
        }else if (criteria.getOperation().equalsIgnoreCase("%")) {
return builder.like(
                        root.<String>get(criteria.getKey()), "%" + criteria.getValue() + "%");        }
}

SearchCriteria.java

private String key;
    private String operation;
    private Object value;
getter, setter, constructor

PeopleService.java

public interface PeopleService{


    public List<People> searchPeople(Integer peopleAge, StringhomeName);

PeopleServiceImpl.java

    public class PeopleServiceImpl implements PeopleService {

        @Autowired
        PeopleRepository peopleRepository;

        @Override
        public List<People> searchPeople(Integer peopleAge, String homeName) {
            peopleAge = 20;
            homeName = "example";
            PeopleSpecification condition1 = null;
            if (peopleAge!= null) {
                nameCond = new PostSpecification(new SearchCriteria("peopleAge", "==", peopleAge));            
            }

            PeopleSpecification condition2 = null;
            if (StringUtils.isNotBlank(homeName)) {
                nameCond = new PostSpecification(new SearchCriteria("homeName", "%", homeName));            
            }

    return postRepository.findAll(Specifications.where(condition1).and(condition2);
}}

我想加入像sql这样的人和家,如下所示:

  

SELECT * FROM people p INNER JOIN home h ON p.peopleId == h.peopleId   在哪里p.age = 20 AND h.homeName如“%example%”

如何在复杂条件下实施?

0 个答案:

没有答案