我查看了许多示例并尝试了各种 w/&w/o 示例匹配器约束,但是无论我通过示例进行查询都只返回 null。
我能够毫无问题地使 CRUD 存储库数据调用正常工作,但是我将其扩展到 JPA 存储库并添加了 QueryByExampleExecutor 接口。findOne() 似乎不起作用。
使用 Spring Boot 2.2.6.RELEASE、spring-boot-starter-data-jpa 和 mysql 5.7。
使用示例查询时,是否需要完成整个对象才能匹配?换句话说,所有的二传手都需要正确的信息吗?还是只是要匹配的对象数据项?
是的,数据库确实只包含一个我试图匹配的正确字符串。
顾客
@Entity
@Table(name="customer")
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="social_security_number")
private String socialSecurityNumber;
//Other data fields are included
}
客户资料库
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
QueryByExampleExecutor
import java.util.Optional;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public interface QueryByExampleExecutor<T> {
<S extends T> Optional<S> findOne(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example, Sort sort);
<S extends T> Page<S> findAll(Example<S> example, Pageable pageable);
<S extends T> long count(Example<S> example);
<S extends T> boolean exists(Example<S> example);
}
客户服务
public interface CustomerService {
public Customer findBySSN(String ssn);
}
CustomerServiceImpl
@Service
public class CustomerServiceImpl implements CustomerService {
private CustomerRepository customerRepository;
@Autowired
public CustomerServiceImpl(CustomerRepository theCustomerRepository) {
customerRepository = theCustomerRepository;
}
@Override
public Customer findBySSN(String ssn) {
//Create a new object to use as a basis for querying against
Customer customer = new Customer();
//Set the parameters for the query
customer.setSocialSecurityNumber(ssn);
//Create an example query
Example<Customer> customerExample = Example.of(customer);
Optional<Customer> result = customerRepository.findOne(customerExample);
if (result.isPresent()) {
return result.get();
} else {
// Didn't find the customer
throw new ObjectNotFoundException("Customer", "Social Security Number ("+ssn+") not found...");
}
}
}
调用方法
@Autowired
private CustomerService customerService;
Customer ssnCustomer = customerService.findBySSN("123456789");
if(ssnCustomer == null) {
System.out.println("SSN NOT FOUND WAS NULL");
} else {
System.out.println("SSN FOUND "+ssnCustomer.getId());
}
我错过了什么?先感谢您。