[0608] 자바 웹 개발 과정🌞

Let's TECH🧐·2021년 6월 8일
0

자바 웹 개발 과정

목록 보기
25/31
post-thumbnail

Controller, Service, Dao, Mapper 분리

  • NoticeController
@Controller("adminNoticeController")
@RequestMapping("/admin/notice/") // url이 기니까 줄이자!
public class NoticeController {
	
	@Autowired
	private NoticeService service; // 컨테이너에서 뽑아서 service에 넣어줌(service를 컨테이너에 넣기 위해 @service annotation 설정)

	@RequestMapping("list")
	public String list(Model model) { // 모델을 얻는 작업
		
		List<Notice> list = service.getList(1, "title", "t");
  • NoticeServieImp
@Service
public class NoticeServiceImp implements NoticeService {
	
	// 필드 인젝션
	@Autowired
	private NoticeDao dao;
		
	// 생성자 인젝션
	/*
	@Autowired
	public NoticeServiceImp(NoticeDao noticeDao) {
		// 가져오자마다 다른 초기화 로직이 동작하게 할 수 있다
	}*/

	// 구현체 얻기, 업무 로직 짜는 곳
	@Override
	public List<Notice> getList() {
		List<Notice> list = getList(1, title, "");
		
		return list;
	}
	
	@Override
	public List<Notice> getList(int page, String field, String query) { // field: 키, query: 값으로 들어갈 녀석
		List<Notice> list = dao.getList(page, field, query);

		return list;
	}
  • MyBatisNoticeDao
@Repository
public class MyBatisNoticeDao implements NoticeDao {
	
	@Autowired
	private SqlSession sqlSession; // 스프링 컨테이너에 담겨져 있음, 보따리에 담겨져있으니 autowired로 사용 가능

	@Override
	public List<Notice> getList(int page, String field, String query) {

		NoticeDao mapper = sqlSession.getMapper(NoticeDao.class); // NoticeDao를 구현하고 있는 매퍼 객체를 내놔
		
		return mapper.getList(page, field, query);
	}
  • NoticeDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- mapping을 하게 될 인터페이스를 넣기 -->
<mapper namespace="com.newlecture.web.dao.NoticeDao">

    <select id="getList" resultType="com.newlecture.web.entity.Notice"> <!-- 반환할 때 사용되는 그릇의 형식 적기 -->
    	select * from Notice where ${field} like '%${query}%'
    </select>

</mapper>
<!-- mapper container에게 이 설정이 위치를 application.properties에서 알려줘야 함 -->
  • application.properties
mybatis.mapper-locations=classpath:com/newlecture/web/dao/mybatis/mapper/*Mapper.xml
profile
Minju's Tech Blog

0개의 댓글