2017年6月23日星期五

[Controller/View]資料直接輸出JSON以及XML格式



1.  設定:
僅需在pom.xml加入Jackson相關的depnency

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.json.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.4.0</version> </dependency> <properties> <jackson.json.version>2.4.3</jackson.json.version> </properties>


2. 
接著新增@ResponseBody code到Controller,@RequestMapping中有個參數"produces",用來指定HTTP Content-type,如application/json或是application/xml,新增的code如下:

@Controller @RequestMapping("/dcn") public class DCNController { @Autowired private DCNRepository dcnRepository; ...... @RequestMapping(value="/jsonformat", produces="application/json") public @ResponseBody List restDCNListJson(Model model){ return dcnRepository.findAll(); } @RequestMapping(value="/xmlformat", produces="application/xml") public @ResponseBody List restDCNListXml(Model model){ return dcnRepository.findAll(); } }



3.   啟動Sever,JSON部分擷取畫面如下:



參考 :
http://ithelp.ithome.com.tw/articles/10159507

2017年6月20日星期二

JPA One-To-Many Relationship




  1.    One-To-Many Relationship 
  2. 在  BookCategory class 設定  One-To-Many  : 
@Entity
@Table(name = "book_category")
public class BookCategory {
    private int id;
    private String name;
    private Set<Book> books;

    @OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)
    public Set<Book> getBooks() {
        return books;
    }

3.  建立BookCategoryRepository 繼承   JpaRepository 

import com.hellokoding.jpa.model.BookCategory;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookCategoryRepository extends JpaRepository<BookCategory, Integer>{
}


4.  可以使用Repository 已經實作好,常用的CRUD功能
(findOne,findAll,save....)  



        // save a couple of categories
        BookCategory categoryA = new BookCategory("Category A");
        Set bookAs = new HashSet<Book>(){{
            add(new Book("Book A1", categoryA));
            add(new Book("Book A2", categoryA));
            add(new Book("Book A3", categoryA));
        }};
        categoryA.setBooks(bookAs);

        BookCategory categoryB = new BookCategory("Category B");
        Set bookBs = new HashSet<Book>(){{
            add(new Book("Book B1", categoryB));
            add(new Book("Book B2", categoryB));
            add(new Book("Book B3", categoryB));
        }};
        categoryB.setBooks(bookBs);

        bookCategoryRepository.save(new HashSet<BookCategory>() {{
            add(categoryA);
            add(categoryB);
        }});

        // fetch all categories
        for (BookCategory bookCategory : bookCategoryRepository.findAll()) {
            logger.info(bookCategory.toString());
        }
    }


5.  完整範例 :




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功能有以下: