A simple introduction to the use of the scene, the DAO layer with Spring Data implementation, DAO only interface, implementation class is the container startup dynamic bytecode generation, interface definition method, method @query write JPQL query statement.
Based on the above limitations, if you make a query to an entity, there are multiple conditions, and each condition is not required. Parameters must be passed, null or empty string must not be, this afternoon, the project team was confronted with this problem.
I've done it before, but the code didn't find it, I tried it again, and then I lost the code to pg.
This time the code is put out, save to lose again, the code is as follows:
DAO interface
?
123456 |
public interface ActivityDao
extends JpaRepository<Activity, Integer> {
@Query
(
"SELECT a FROM Activity a WHERE (a.code=:code OR :code = null) AND (a.name=:name OR :name = null)"
)
public List<Activity> findByCodeAndName(
@Param
(
"code"
) String code,
@Param
(
"name"
) String name);
}
|
Junit
?
1234567891011121314 |
@RunWith
(SpringJUnit4ClassRunner.
class
)
@ContextConfiguration
(locations =
"classpath:META-INF\\appContext.xml"
)
public class ActivityDaoTest
extends AbstractJUnit4SpringContextTests {
@Resource
private ActivityDao dao;
@Test
public void test() {
// List<Activity> list = dao.findByCodeAndName("33", "3");
List<Activity> list = dao.findByCodeAndName(
"33"
,
null
);
System.out.println(list.size());
}
}
|
Spring Data JAP multiple query condition processing not required