public class Foo{
private String foo;
private String bar;
//class methods
}
public List<Foo> findByFooBarContains(@Param("bar")String bar) {
TypedQuery<Foo> query = entityManager.createQuery("SELECT foo FROM Foo foo WHERE foo.bar LIKE '%:bar%'", Foo.class);
return query.getResultList();
}
I've tested with JPA standard findByName contains and it is working as it should. However my custom query is returning nothing. what am I doing wrong?
Assuming that you have a JPA repository interface, you can simply define a query method like:
public interface FooRepo extends JpaRepository<FooRepo, String>{
//Query Method
List<Foo> findByBarContains(String bar);
}
You can then call this method from your Service like:
@Service
public class FooService {
@Autowired
private FooRepo fooRepo;
public List<Foo> fetchByBarContains(String bar){
return fooRepo.findByBarContains(bar);
}
}
You can also implement native or JPQL queries by defining them in your Repository like:
//JPQL (foo here is your model and not the table)
@Query("SELECT foo FROM Foo WHERE bar LIKE %?1%")
List<Foo>findByBarContains(String bar);
//Native
@Query(
value = "SELECT foo FROM Foo WHERE bar LIKE %?1%",
nativeQuery = true)
List<Foo>findByBarContains(String bar);
Of course, your model should be Annotated with @Entity like:
@Entity(name="Foo")
public class Foo{
@Id
private String foo;
//Use @Column annotation if your database column has a different name than your field
@Column(name = "BAR")
private String bar;
// getters and setters
}
On the other hand, if you want to use entity manager, you can do:
public List<Foo> findByFooBarContains(String bar) {
return entityManager.createQuery(
"SELECT foo FROM Foo foo WHERE foo.bar LIKE %:bar%", Foo.class)
.setParameter("bar", bar)
.getResultList();
}
I think the ".setParameter("bar", bar)" is what you're missing in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.