Last active
November 15, 2015 01:19
-
-
Save tigawa/fcfc9ec183d9115ecf0a to your computer and use it in GitHub Desktop.
複数検索項目、ページネーションに対応した custom Repositoryクラス ※動作検証していません
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Repository | |
public interface UserRepository extends | |
JpaRepository<User, Long>, | |
JpaSpecificationExecutor<User>, | |
UserRepositoryCustom {} | |
@Repository | |
public interface UserRepositoryCustom { | |
public List<User> findUsers(Map<String,Object> params); | |
} | |
@Repository | |
public class UserRepositoryImpl implements UserRepositoryCustom { | |
@Autowired | |
EntityManager entityManager; | |
public List<User> findUsers(Map<String,Object> params) { | |
StringBilder sql = new StringBilder(); | |
// params をもとに動的SQLを生成 | |
sql.append("SELECT c FROM User c WHERE c.name = :name"); | |
TypedQuery<User> query = entityManager.createQuery(sql, User.class); | |
for(Map.Entry<String, Object> e : params.entrySet()){ | |
query.setParameter(e.getKey(), e.getValue()); | |
} | |
int pageNumber = 1; | |
int pageSize = 10; | |
query.setFirstResult((pageNumber-1) * pageSize); | |
query.setMaxResults(pageSize); | |
return query.getResultList(); | |
} | |
} | |
// link | |
// https://terasolunaorg.github.io/guideline/public_review/ArchitectureInDetail/DataAccessJpa.html#id20 | |
// http://www.objectdb.com/java/jpa/query/parameter | |
// http://qiita.com/tag1216/items/55742fdb442e5617f727 | |
// http://www.baeldung.com/jpa-pagination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment