방카@Dev
[Spring]MyBatis 본문
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&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";
}
}
'BackEnd > Spring' 카테고리의 다른 글
[Spring] Scope 객체를 이용한 데이터 전송 방법(Request,Model,Session) (0) | 2024.06.24 |
---|---|
[Spring]빈 생명주기 콜백 (0) | 2024.06.21 |
[Spring]JDBC Template 정리 (0) | 2024.06.20 |
[Spring]게시판 파일 업로드 라이브러리(COS) (1) | 2024.06.20 |
[Spring]Validator를 이용한 유효성 검사 (0) | 2024.06.17 |