JPA와 Vue를 이용한 목록 조회

세피·2022년 1월 17일
0

스프링

목록 보기
8/11

Spring 목록 조회

BoardController.java

@Slf4j // 이것을 선언했으므로, 더는 logger를 new 해서 쓰지 않아도 된다.
@RestController
@RequestMapping("api") // @RequestMapping("api")를 입력하면, http://[ip]:[port]/api 와 같이 url이 매핑된다.
public class BoardController {
	
	@Autowired
	private  BoardService boardService;
	//@ResponseBody
	/*
	 * 	@ResponseBody 를 사용하면 java 객체를 json으로 안바꿔줘도 됨. resp 객체에 직접 담을 일이 없음.
	@ResponseBody 를 이용하면 자바객체 그대로 반환하여 사용 가능.
	@Controller 대신 @RestController 를 쓰면 @ResponseBody를 선언하지 않아도 된다
	 * */
	

	//게시판 목록 불러오기
	@GetMapping(value = "/boardList", produces = { MediaType.APPLICATION_JSON_VALUE })
	public ResponseEntity<List<BoardDto>> boardList(Model model) {
		List<BoardDto> boardList = this.boardService.findAll();
		log.info("boardList == " + boardList); 
		return new ResponseEntity<List<BoardDto>>(boardList, HttpStatus.OK);
	}

https://devmoony.tistory.com/103

@RestController (@responsebody 안써도 됨)

@ResponseBody (덕분에 modelandview로 view까지 안 넘겨줌) 는 짝궁으로 외우고

ResponseEntity가 있음.

데이터와 코드(http 응답코드 404 같은..)를 같이 보내줌

BoardServiceImpl.java

@Service
public class BoardServiceImpl  implements BoardService{

	@Autowired
	private BoardRepository boardRepository;
	
	@Override
	public List<BoardDto> findAll() {
		List<BoardEntity> list = this.boardRepository.findAll();
		ModelMapper modelMapper = new ModelMapper();
		List<BoardDto> resultList =  Arrays.asList(modelMapper.map(list, BoardDto[].class));	
		return resultList;
	}

}

BoardService

public interface BoardService {
	List<BoardDto> findAll(); // 목록 불러오기
}

BoardRepository.java

@Repository	  // 따로 쿼리문 작성없이 생성, 조회, 업데이트, 삭제(CRUD)를 할 수 있게 기능을 제공
public interface BoardRepository extends JpaRepository<BoardEntity, String>{
	public List<BoardEntity> findAll();
}

BoardDto

@Getter
@Setter
@ToString
public class BoardDto {

	private int idx;
	
	private String title;
	
	private String content;
	
	private String userId;
	
	private LocalDateTime  createDate;
	
	private LocalDateTime  updateDate;
}

BoardEntity

@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "board_info")
@Entity
public class BoardEntity {
	
	//	롬복 애너테이션
	/*
	 *  @Getter / @Setter
	 *  @ToString : toString() 메서드 생성, @ToString(exclude = “필드명”)을 사용하여 원하지 않는 필드는 제외할 수 있다.
	 *  @EqualsAndHashCode : 자바의 equals(: 두 객체의 내용이 같은가)  메서드와 hashCode(: 두 객체가 같은 객체인가) 메서드 생성
	 *  @NoArgsConstructor : 매개 변수가 없는 기본 생성자 생성
	 *  @AllArgsConstructor : 객체의 모든 필드값을 인자로 받는 생성자 생성
	 *  @RequiredArgsConstructor : final필드와 @NonNull 어노테이션이 붙은 필드에 대한 생성자를 생성하여 특정 변수만을 활용하는 생성자를 생성해 준다.
	 * */

	/*
	 * 규칙
		이름 매핑, 단어와 단어 구분시 자바 언어는 관례상 roleType과 같이 카멜 표기법을 쓰고
		데이터베이스는 role_type과 같이 _ 를 써준다.
	 * */
	
	@Id
	@Column(name = "idx")
	private int idx;
	
	@Column(name = "title")
	private String title;
	
	@Column(name = "content")
	private String content;
	
	@Column(name = "user_id")
	private String userId;
	
	/*
	 * @Temporal 날짜타입 매핑시 사용
	 * TemporalType.TIMESTAMP 타임스탬프 타입과 매핑 (날짜 + 시간)
	 * TemporalType.DATE 2021-01-01 date 타입과 매핑
	 * TemporalType.TIME 시간과 매핑 11:11:11
	 * */

	@CreationTimestamp
	//@Temporal(TemporalType.DATE)
	@Column(name = "create_date", nullable = false)
	private LocalDateTime  createDate;
	
	@UpdateTimestamp
	@Column(name = "update_date", nullable = false)
	private LocalDateTime  updateDate;


}

===============================

이제 Vue

main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import axios from 'axios'
import BoardList from './views/board/BoardList'

// router 기능 확장 선언
Vue.use(VueRouter);

// axios 기능 확장 선언
Vue.use(axios);
Vue.prototype.$http = axios;
Vue.prototype.$axios = axios;

// 이곳에 router 를 등록
const routes = [
	{ path: '/api/boardList', name: 'BoardList', component: BoardList }	
];

// router 객체생성
const router = new VueRouter({
  routes
});

new Vue({
  render: h => h(App)
 ,router // router 추가
 ,axios
}).$mount('#app')

header.vue

<router-link :to="{ name : 'BoardList' }">BoardList</router-link>

BoardList.vue

<template>
   <div>
      <h1>boardList</h1>
      <a href="javascript:;" @click="getList">GET 방식 데이터 접근(콘솔로그확인)</a>
      <table>
         <thead>
            <th>번호</th>
            <th>제목</th>
            <th>내용</th>
            <th>등록일</th>
         </thead>
         <!-- for 루프 값 중 하나를 key로 설정 할 수 있으며 vue 버전이 업데이트 되면서 key를 무조건 설정해주게끔 바뀌었다.
               index를 활용해 아이템의 순서를 보여줄 수 있다. 
               <v-for="(각 요소를 할당할 변수 이름 , index) in 반복 대상 배열 또는 객체" :key="변수의 key 값">
           -->
         <tr v-for="(item, index) in items" :key="index">
            <td>{{item.idx}}</td>
            <td>{{item.title}}</td>
            <td>{{item.content}}</td>
            <td>{{item.createDate}}</td>
         </tr>
      </table>
   <router-link to="/api/BoardWrtie"><button>글 등록</button></router-link>
   </div>
</template>

<script>
export default {
   name : 'BoardList',
   data() {
      return {
         title :"",
         items : []
      }
   },
   mounted() {
      this.getList()
   },

   // 원하는 메소드명(함수명)에 data()에 있는 변수를 넣어서 v-bind 혹은 : 로 가져가 쓸 수 있다. 
   methods : {
      // getList 안에는 items라는 변수가포함되어있다.
      getList() {
         this.$axios.get("/api/boardList")
            .then((res) => {
               console.log(res);
               // this.items 는 위에 data() 안에 변수중 하나이다.
               this.items = res.data;
            })
            .then((err) => {
               console.log(err);
            })
      }
   }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
profile
세피의 블로그입니다

0개의 댓글