본문 바로가기
수업(국비지원)/Mybatis

[MYBATIS] (MVC 2) ItemDao, ItemMapper

by byeolsub 2023. 4. 21.

 📌 ItemDao.java 내용 수정

package dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import javax.validation.Valid;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import dao.mapper.ItemMapper;
import logic.Item;

/*
 *  @Component : 해당 클래스를 객체화
 *   - model 기능 : db와 연결된 클래스
 */

@Repository //@Component(객체를 만들어주는) + model 기능
public class ItemDao {
	@Autowired //sqlSessionTemplate 객체 주입
	private SqlSessionTemplate template;
	private Map<String,Object> param = new HashMap<>();
	public List<Item> list() { 
		//mapper : db의 컬럼명과 mapper에 지정된 Item 클래스의 프로퍼티를 비교하여 Item 클래스에 객체로 저장
		//query() : select 구문의 결과가 여러개의 레코드 가능
		return template.getMapper(ItemMapper.class).select();
	}
	
	public Item getItem(Integer id) {
		param.clear();
		param.put("id", id);
		return template.getMapper(ItemMapper.class).getItem(param);
	}

	//item 테이블의 id 값 중 최대값 리턴
	public int maxId() {
		//Integer.class : 리턴값의 자료형 설정
		return template.getMapper(ItemMapper.class).maxId();
	}
	
	//db에 등록 해주는 
	public void insert(Item item) {	
		template.getMapper(ItemMapper.class).insert(item);
	}

	public void update(Item item) {
		template.getMapper(ItemMapper.class).update(item); //db에 수정
	}

	public void delete(Integer id) {
		param.clear();
		param.put("id", id);
		template.getMapper(ItemMapper.class).delete(param);
	}
}

 

 

📌 ItemMapper.java 생성

package dao.mapper;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import logic.Item;

public interface ItemMapper {

	@Select("select * from item order by id")
	List<Item> select();

	@Select("select * from item where id=#{id}")
	Item getItem(Map<String, Object> param);

	@Select("select nvl(max(id),0) from item")
	int maxId();

	@Insert("insert into item (id, name, price, description, pictureUrl) values (#{id},#{name},#{price},#{description},#{pictureUrl})")
	void insert(@Valid Item item);

	@Update("update item set name=#{name}, price=#{price}, description=#{description}, pictureUrl=#{pictureUrl}"
			   + " where id=#{id}")
	void update(Item item);

	@Delete("delete from item where id=#{id}")
	void delete(Map<String, Object> param);
	
}