2017年6月20日星期二

CrudRepository



原本, 沒有使用 CrudRepository 前, 要在DAO layer中 , 實作CRUD的程式碼.


改用CrudRepository之後 , 基本的CRUD 程式碼可以省略 , CrudRepository  自動幫你處理.


1.    Create Repository interface

package org.arpit.java2blog.repository;

import org.arpit.java2blog.model.Country;
import org.springframework.data.repository.CrudRepository;

public interface CountryRepository extends CrudRepository
}


2.  原本 ,  service class 中, @Autowired Dao , 現在改為 : 

@Autowired
 CountryRepository countryRepository;



3. 然後, 在service class中  ,  可以使用基本的CRUD功能,

不需要寫 code,不須寫SQL或HQL,
因為CountryRepository 繼承CrudRepository
所以可以直接使用 CrudRepository  提供的method :

  countryRepository.save(country);
  countryRepository.findOne(id);
  countryRepository.findAll();
  countryRepository.delete(id);


4.  Service 範例如下:

@Service("countryService")
public class CountryService {

 @Autowired
 CountryRepository countryRepository;

 @Transactional
 public List getAllCountries() {
  List countries=new ArrayList();
  Iterable countriesIterable=countryRepository.findAll();
  Iterator countriesIterator=countriesIterable.iterator();
  while(countriesIterator.hasNext())
  {
   countries.add(countriesIterator.next());
  }
  return countries;
 }

 @Transactional
 public Country getCountry(int id) {
  return countryRepository.findOne(id);
 }

 @Transactional
 public void addCountry(Country country) {
  countryRepository.save(country);
 }

 @Transactional
 public void updateCountry(Country country) {
  countryRepository.save(country);

 }

 @Transactional
 public void deleteCountry(int id) {
  countryRepository.delete(id);
 }

}



5. 完整範例請參考:


 http://www.java2blog.com/2016/09/spring-mvc-spring-data-hibernate-mysql-example.html




6. CrudRepository 提供的CRUD功能有以下: 

沒有留言: