Google Code Prettify

2017年1月28日 星期六

spring data: PagingAndSortingRepository

在「spring data: CrudRepository 自動生成」有說明過 spring data 的 CrudRepository,提供了許多實用的預設 method,方便程式員進行資料庫的 CRUD 操作,這篇說明另一個好用的介面 PagingAndSortingRepository,只要宣告一個繼承這個介面的介面,即可以輕鬆擁有查詢翻頁的功能,也就是在網頁中,如果查詢結果很多會分成很多頁面時,可以使用這個介面提供的預設 method,它會傳回指定頁次的結果。
假設網站管理者要查詢網站中的使用者,並進行管理,就可以用到這個介面。
public interface UsersDAO extends PagingAndSortingRepository<Users, String> {
    public List<Users> findByEmail(String email);
    //public Page<Users> findAll(Pageable p);
}
上面的 UserDAO 繼承了 PagingAndSortingRepository 介面,於是我們不需要寫任何程式,就可以使用 findAll 等預設的介面,上面 findAll 只是我寫出來讓大家知道 spring data 中是怎麼宣告,實際上是不需要寫出來,測試程式如下:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebInitializer.class, RootConfig.class, JpaConfig.class, MvcConfig.class })
@ActiveProfiles("TEST")
public class UserDAOTest {
    @Autowired
    private UsersDAO dao;
    
    @Transactional
    @Test
    public void testFindAll() {
        Pageable p = new PageRequest(0, 5);
        Page<Users> all = dao.findAll(p);
        all.forEach(u -> System.out.println(u.toString()));
    }
} 
看一下紅色部份,dao 直接可以呼叫 findAll,參數傳入的是指定資料結果每 5 筆資料一頁,要傳回的是第 1 頁 (0 代表第一頁、1 代表第二頁…)。至於前面的 @WebAppConfiguration,這只是因為這個程式是 spring MVC 程式,所以在初始化時,會帶入一些 web 相關的物件,所以要這麼寫才不會有錯,如果不是 web 程式,就不需要這個 annotation。另外一提的是,不管 CrudRepository 或 PagingAndSortingRepository,spring data 都提供了預設 method 以外的一個規範,只要規循該規範定義 method,spring data 就可以自動產生相關的程式,例如上面的 findByEmail,這個 method 就可以用來搜尋特定 email 的使用者,spring data 還可以根據我們宣告的傳回值判斷傳回的是一個或多個結果,測試程式如下:
    @Transactional
    @Test
    public void testFindByEmail() {
        Users user = dao.findByEmail("hi.steven@gmail.com");
        assertNotNull(user);
        System.out.println(user.toString());
    }
spring data 提供的規範有那些? 可以參考「Professional Java for Web Applications - Featuring WebSockets, Spring Framework, JPA Hibernate and Spring Security」第 641 頁,內容如下:
Is and Equals are implied in the absence of other keywords, but you may explicitly use them. For example, findByIsbn is equivalent to findByIsbnIs and findByIsbnEquals.
Not and IsNot negate any other keyword except for Or and And. Is and Equals are still implied in the absence of other keywords, so findByIsbnIsNot is equivalent to findByIsbnIsNotEqual.
After and IsAfter indicate that the property is a date and/or time that should come after the given value, whereas Before and IsBefore indicate that the property should come
before the given value. Example: findByDateFoundedIsAfter(Date date).
Containing, IsContaining, and Contains indicate that the property’s value may start and end with anything but should contain the given value. This is similar to StartingWith, IsStartingWith, and StartsWith, which indicate that the property should start with the specified value. Likewise, EndingWith, IsEndingWith, and EndsWith indicate that the property should end with the specified value.
Example:
findByTitleContains(String value) is equivalent to the SQL criteria WHERE title = '%value%'.
Like is similar to Contains, StartsWith, and EndsWith, except that value you provide should already contain the appropriate wildcards (instead of Spring Data adding them for you). This gives you the flexibility to specify more advanced patterns. NotLike simply negates Like. Example: findByTitleLike(String value) could be called with value "%Catcher%Rye%" and would match “The Catcher in the Rye” and “Catcher Brings Home Rye Bread.”
Between and IsBetween indicate that the property should be between the two specified values. This means that you must provide two parameters for this property criterion. You can use Between on any type that may be compared mathematically in this manner, such as numeric and date types. Example: findByDateFoundedBetween(Date start, Date end).
Exists indicates that something should exist. Its meaning may vary wildly between storage mediums. It is roughly equivalent to the EXISTS keyword in JPQL and SQL.
True and IsTrue indicate that the named property should be true, whereas False and IsFalse indicate that the named property should be false. These keywords do not require method parameters because the value is implied by the keywords themselves. Example: findByApprovedIsFalse().
GreaterThan and IsGreaterThan indicate that the property is greater than the parameter value. You can include the parameter value in the bounds with GreaterThanEqual or IsGreaterThanEqual. The inverse of these keywords are LessThan, IsLessThan, LessThanEqual, and IsLessThanEqual.
In indicates that the property value must be equal to at least one of the values specified. The parameter matching this criterion should be an Iterable of the same type of the property.
Example: findByAuthorIn(Iterable<String> authors).
Null and IsNull indicate that the value should be null. These keywords also do not require method parameters because the value is implied.
Near, IsNear, Within, and IsWithin are keywords useful for certain NoSQL database types but have no useful meaning in JPA.
Regex, MatchesRegex, and Matches indicate that the property value should match the String regular expression (do not use Pattern) specified in the corresponding method parameter.






【美影 - 關鍵少數】
這部電影是由真人真事改編,時代是1960年,當時美國還是個種族歧視、性別歧視非常嚴重的國家,許多學校不但不准黑人入學,也不准女性入學,在 NASA 卻有一群優秀的黑人女性科學家,在雙重壓迫下,為美國的太空競賽默默的作出重大的貢獻。

劇中的科學家白人全部是男性,黑人全部是女性,這是一個很怪的狀況,但是電影中沒有解釋原因,因為在種族、性別的雙重歧視下,白人女性、黑人男性應該更有機會進入 NASA,為什麼偏偏是最被歧視的黑人女性成為裡面的關鍵少數?
撇開上面的疑惑不談,電影中相當精典的橋段,如上圖,主角在黑板上寫下她的發現。在電腦進入 NASA 協助運算前,NASA 竟然養了一大群數學高手充當人肉計算機,這些人除了頭腦要好,看來體力也要不錯,不然沒能力在梯子上爬上爬下,恐怕也沒有表現的機會。

沒有留言:

張貼留言