Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

방카@Dev

[Spring]MyBatis 본문

BackEnd/Spring

[Spring]MyBatis

방카킴 2024. 6. 25. 11:28

 

mybatis – 마이바티스 3 | 시작하기

 

mybatis.org

 

1. pom.xml 에 의존성 추가

<!-- MyBatis -->		
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.2.8</version>
</dependency>		
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>

2. servlet-context.xml 빈즈 생성

<beans:bean id="dataSource"
       class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
    <beans:property name="url" 
       value="jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC&amp;useSSL=false" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="qwe123!@#" />
</beans:bean>

<beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
    <beans:property name="mapperLocations" value="classpath:com/javalec/spring_mybatis/dao/mapper/*.xml"></beans:property>
</beans:bean>

<beans:bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <beans:constructor-arg index="0" ref="sqlSessionFactory"></beans:constructor-arg>
</beans:bean>

 

3. IDao 인터페이스 작성

public interface IDao {
	
	public ArrayList<ContentDto> listDao();
	public void writeDao(String mWriter, String mContent);
	public ContentDto viewDao(String strID);
	public void deleteDao(String bId);
}

 

4. IDao.xml 쿼리문 작성

<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
	
<mapper namespace="com.javalec.spring_mybatis.dao.IDao">
	
	<select id="listDao" resultType="com.javalec.spring_mybatis.dto.ContentDto">
		SELECT * FROM BOARD2 ORDER BY MID DESC
	</select>
	
	<insert id="writeDao">
		INSERT INTO BOARD2 (MID, MWRITER,MCONTENT) VALUES (0,#{param1},#{param2})
	</insert>
	
	<delete id="deleteDao">
		DELETE FROM BOARD2 WHERE MID=#{param1}
	</delete>
	
</mapper>

 

5. Controller 변경

@Controller
public class HomeController {

	@Autowired
	private SqlSession sqlSession;
    
    	@RequestMapping("/list")
	public String list(Model model) {
//		ArrayList<ContentDto> dtos = dao.listDao();
		IDao dao = sqlSession.getMapper(IDao.class);
		
//		model.addAttribute("list", dtos);
		model.addAttribute("list",dao.listDao());
		
		return "/list";
	}
}