admin/insertbatch - 일괄등록
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "book4")
public class Book {
@Id
private long code = 0L;
private String title = null;
private long price = 0L;
private String writer = null;
// 문자열 = "Hello"
// 문자하나 = 'A', 'B', 'C'
private char category;
private Date regdate = null;
}
@Service
@Service
public interface BookDB {
// 일괄등록
public long insertBatchBook(List<Book> list);
}
@Service
List<Book>
타입으로 파라미터를 넘긴다.
mongoDB.insert
중에서 List 타입을 받는 생성자를 선택한다.
List를 던지면 반환받는 값이 Collection
이다
3-1. 반환값을 Collection 타입으로 정의해두면 Collection 아래의 자식타입을 모두 사용할수 있다.
3-2. 하지만 Collection 자체만으로는 객체를 생성할수 없다. abstract 추상화 되었기 때문.
// 1. 서비스
@Service
public class BookDBImpl implements BookDB { // 2. 설계 인터페이스 구현
// 3. DB연동 객체 생성
@Autowired
MongoTemplate mongodb;
@Override
public long insertBatchBook(List<Book> list) {
try {
// 4. 실제수행(구현)
// Collection 타입으로 정의해두면 Collection 아래의 자식타입을 모두 사용할수 있다.
// 하지만 Collection 자체만으로는 객체를 생성할수 없다. abstract 추상화 되었기 때문.
Collection<Book> retList = mongodb.insert(list, Book.class);
if (retList.size() == list.size()) {
return 1;
}
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
@GetMapping(value = "/insertbatch")
// 127.0.0.1:8080/admin/insertbatch
@GetMapping(value = "/insertbatch")
public String insertbatchGET(Model model) {
model.addAttribute("title", "책 등록");
return "admin/insertbatch";
}
@RequestParam
으로 받는다._id
)를 생성한다.@Autowired
SequenceService sequenceService;
List<Book> list = new ArrayList<>();
)에 Book 타입의 book을 목록 형태로 담는다(list.add(book);
).
// 도서 일괄 등록
// 127.0.0.1:8080/admin/insertbatch
@PostMapping(value = "/insertbatch")
public String insertbatchPOST(
@RequestParam(name = "title") String[] title,
@RequestParam(name = "price") long[] price,
@RequestParam(name = "writer") String[] writer,
@RequestParam(name = "category") char[] category) {
// long code = sequenceService.generationSequence("SEQ_BOOK4_NO");
// 빈 리스트 만들기
List<Book> list = new ArrayList<>();
for (int i = 0; i < title.length; i++) {
// System.out.println(title[i] + "," + price[i] + "," + writer[i] + "," +
// category[i]);
// book 객체만들기
// 시퀀스를 이용해서 코드를 채움, 날짜도
// 리스트 추가하기
Book book = new Book();
book.setCode(sequenceService.generationSequence("SEQ_BOOK4_NO"));
book.setTitle(title[i]);
book.setPrice(price[i]);
book.setWriter(writer[i]);
book.setCategory(category[i]);
book.setRegdate(new Date());
// System.out.println("book ==> " + book);
list.add(book);
}
// System.out.println("list ==> " + list);
// 배열 4개로 되어있는 결과를 => List<Book>
long ret = bookDB.insertBatchBook(list);
// System.out.println("ret ===> " + ret);
if (ret == 1) {
return "redirect:/admin/insertbatch";
}
return "redirect:/admin/insertbatch";
}
admin/action - 일괄수정/삭제
@Service
// 일괄삭제
public long deleteBatchBook(List<Long> code);
List<Long> code
를 받는다.List<Book>
로 반환한다.List<Book> list
를 받는다.// 수정 목록 보내기 (수업용)
public List<Book> updateBatchListWhereIn(List<Long> code);
// 일괄수정 (수업용)
public long updateBatchBook(List<Book> list);
@Service
List<Long>
형태이기 때문에 여러개가 일치해야 하는 조건이므로query.addCriteria(Criteria.where("_id").in(code));
@Override
public List<Book> updateBatchListWhereIn(List<Long> code) {
try {
Query query = new Query();
query.addCriteria(Criteria.where("_id").in(code));
// DESC : 내림차순
// ASC : 오름차순
Sort sort = Sort.by(Direction.DESC, "_id");
query.with(sort);
return mongodb.find(query, Book.class);
// System.out.println("result ===> " + result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
_id
를 찾아서 해당 사항을 모두 수정하는 형태를 만들어서 반복문을 돌린다.@Override
public long updateBatchBook(List<Book> list) {
try {
long updateCnt = 0L;
for (Book tmp : list) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(tmp.getCode()));
Update update = new Update();
update.set("title", tmp.getTitle());
update.set("price", tmp.getPrice());
update.set("writer", tmp.getWriter());
update.set("category", tmp.getCategory());
UpdateResult result = mongodb.updateFirst(query, update, Book.class);
updateCnt += result.getMatchedCount();
}
if (updateCnt == list.size()) {
return 1;
}
return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@RequestParam(name = "btn") String btn
으로 jsp의 버튼의 value값을 받아온다.@RequestParam(name = "chk") List<Long> code
으로 jsp에서 체크한 항목의 code를 List타입으로 받아온다.일괄삭제
일때 수행 할 명령을 if문을 통해 만든다.if (btn.equals("일괄삭제")) { }
@PostMapping
으로는 jsp를 불러올수 없기때문에 redirect
를 사용해야한다.redirect
를 사용하면 변수나 받은 값 등이 남아 있지 않고 초기화 되어버린다.code
를 @GetMapping
하는 타이밍에 던져주기위해 세션에 저장한다.httpSession.setAttribute("CHK", code);
@Bean
public JdkMongoSessionConverter jdkMongoSessionConverter() {
return new JdkMongoSessionConverter(Duration.ofMinutes(10));
}
@GetMapping
타이밍에 "CHK"
라는 name을 이용해서 세션에서 code
를 꺼낼 수 있다.// 일괄수정/삭제
@PostMapping(value = "/action")
public String actionPOST(
@RequestParam(name = "btn") String btn,
@RequestParam(name = "chk") List<Long> code) {
if (btn.equals("일괄삭제")) {
long response = bookDB.deleteBatchBook(code);
if (response == 1) {
return "redirect:/admin/selectlist";
}
return "redirect:/admin/selectlist";
}
else if (btn.equals("일괄수정")) {
httpSession.setAttribute("CHK", code);
return "redirect:/admin/updatebatch";
}
return "redirect:/admin/selectlist";
}
@GetMapping
페이지code
를 불러와서 사용한다.code
의 타입은 List이고, 조회하는 메소드도 List<Long>
형태로 받는다.List<Long> code = (List<Long>) httpSession.getAttribute("CHK");
@SuppressWarnings({ "unchecked" })
List<Long> code
임을 알고 있기 때문List<Book> list
를 model 형태로 jsp에 던진다.model.addAttribute("book", list);
// 일괄수정페이지 GET
@GetMapping(value = "/updatebatch")
public String updatebatchGET(Model model) {
// 형변환 경고(데이터가 안전하지 않다)를 없앰
// 세션에 추가할때와 가지고올때의 타입이 정확하게 매칭한다는것을 나는 알고 있기때문
@SuppressWarnings({ "unchecked" })
List<Long> code = (List<Long>) httpSession.getAttribute("CHK");
List<Book> list = bookDB.updateBatchListWhereIn(code);
model.addAttribute("book", list);
return "/admin/updatebatch";
}
@RequestParam
으로 jsp에서 받은 값들의 타입과 변수명을 정한다.@Service
파일에서 정의한 형태로 updateBatchBook을 수행하기 위해 List<Book> list = new ArrayList<>()
를 만든다.bookDB.updateBatchBook(list);
로 List 타입의 list를 넣어 명령을 수행한다.@PostMapping(value = "/updatebatch")
public String updatebatchPOST(
@RequestParam(name = "code") long[] code,
@RequestParam(name = "title") String[] title,
@RequestParam(name = "price") long[] price,
@RequestParam(name = "writer") String[] writer,
@RequestParam(name = "category") char[] category) {
List<Book> list = new ArrayList<>();
for (int i = 0; i < code.length; i++) {
Book book = new Book();
book.setCode(code[i]);
book.setTitle(title[i]);
book.setPrice(price[i]);
book.setWriter(writer[i]);
book.setCategory(category[i]);
list.add(book);
}
long ret = bookDB.updateBatchBook(list);
if (ret == 1) {
System.out.println("수정완료");
return "redirect:/admin/selectlist";
}
return "redirect:/admin/updatebatch";
}