Can we use both spring data specification and spring data projection ? Does spring boot support this?
I want to use specification for filtering and selecting only the columns I needed from the table. So to get only the selected columns, I want to use projection. Can someone let me know how to achieve this? Im new to spring and learning things. Kindly guide me
I have created a project like below,
my entity class:
@Entity
@Table(name="Customer")
public class Customer {
@Id
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
my specification service class:
@Service
public class SpecificationService {
public static Specification<Customer> getCustomerSpecification(String name) {
return new Specification<Customer>() {
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder) {
Path<String> custId = root.get("id");
Path<Integer> customerName = root.get("name");
query.multiselect(custId.alias("CustomerId"),customerName.alias("CustomerName"),
criteriaBuilder.count(criteriaBuilder.literal(1)).alias("Count"));
final List<Predicate> predicates = new ArrayList<>();
if (name != null && !name.equals("")) {
predicates.add(criteriaBuilder.like(root.get("name"), name));
}
query.groupBy(custId, customerName);
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
}
my customer service class:
@Service
public class CustomerService {
@Autowired
CustomerRepository repository;
public void checkSpecification(){
Specification<Customer> spec = SpecificationService.getCustomerSpecification("USA");
List<CustomerProjection> projections = repository.getCustomers(spec);
}
}
my repository class,
@Repository
public interface CustomerRepository extends JpaRepository\<Customer, Integer\>, JpaSpecificationExecutor\<Customer\> {
List<CustomerProjection> getCustomers(Specification<Customer> spec);
}
my projection class,
public interface CustomerProjection {
String getId();
String getName();
Integer getCount();
}
I'm getting the below error :
No property 'getCustomers' found for type 'Customer'