我要作为本机查询执行的操作如下:
SELECT * FROM table WHERE col1 LIKE '%param1%' AND col1 LIKE '%param2%';
但是问题是我可以获得1..N参数,我将如何实现呢?
@Entity
@Table(name = "random")
public class Random implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotEmpty
@Column(nullable = false)
private String col1;
}
public interface IRandomDAO extends JpaRepository<Random, Long>{
public List<Random> findByCol1Containing(String params);
}
public interface IRandomService {
public List<Random> findByCol1Containing(Set<String> params);
}
@Service
public class RandomServiceImpl implements IRecetaService {
@Autowired
private IRecetaDAO recetaDAO;
@Override
public List<Random> findByCol1In(Set<String> params) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Random> query = cb.createQuery(Random.class);
Root<Random> random= query.from(Random.class);
Path<String> paramsPath = random.get("col1");
List<Predicate> predicates = new ArrayList<>();
for (String param: params) {
predicates.add(cb.like(paramsPath , param));
}
query.select(random)
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
}
@CrossOrigin(origins = { "http://localhost:4200" })
@RestController
@RequestMapping("/rest")
public class RandomRestController {
@Autowired
private IRandomService randomService;
@GetMapping("/random")
public ResponseEntity<?> find(@RequestParam String params) {
String[] search = null;
Set<String> searchParams = new HashSet<>();
if (params.contains("-")) {
search = params.split("-");
for (int i = 0; i < search.length; i++) {
// filling the set with any number of items
searchParams.add("%" + search[i] + "%");
}
} else {
searchParams.add("%" + params + "%");
}
Map<String, Object> response = new HashMap<>();
List<Random> listRandom = null;
listRandom = randomService.findByCol1In(searchParams);
if (!listRandom.isEmpty()) {
response.put("mensaje", "found it");
response.put("receta", listRandom);
return new ResponseEntity<Map<String, Object>>(response, HttpStatus.OK);
}
response.put("message", "not found");
response.put("word", searchParams.toString());
return new ResponseEntity<Map<String, Object>>(response, HttpStatus.OK);
}
}
所以问题在于,使用此代码,我得到的查询结果如下:
SELECT * FROM table WHERE col1 LIKE '%param1%';
SELECT * FROM table WHERE col1 LIKE '%param2%';
SELECT * FROM table WHERE col1 LIKE ...N params;
我如何实现:
SELECT * FROM table WHERE col1 LIKE '%param1%' AND col1 LIKE '%param2%' AND col1 LIKE '%Nparams%';
如果我对这个问题做错了事,很抱歉,这是我的第一篇文章。
谢谢!