2019. 4. 17. 12:02ㆍMybatis
#1 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases>
<package name="vo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="org.h2.Driver"/> <property name="url" value="jdbc:h2:tcp://localhost/~/kimjonghyun"/> <property name="username" value="sa"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="dao/mapper/MemberMapper.xml"/> <mapper resource="dao/mapper/BoardMapper.xml" /> </mappers> </configuration> |
#2 boardMapper.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"> <mapper namespace="dao.mapper.BoardMapper">
<select id="getMaxBoardNum" resultType="int"> SELECT MAX(num) FROM board </select>
<insert id="insertBoard" parameterType="board" > INSERT INTO board (num, name, pass, subject, content, filename, re_ref, re_lev, re_seq, readcount, ip, reg_date) VALUES (#{num}, #{name}, #{pass}, #{subject}, #{content}, #{filename}, #{re_ref}, #{re_lev}, #{re_seq}, #{readcount}, #{ip}, CURRENT_TIMESTAMP) </insert>
<select id="getBoards" parameterType="hashmap" resultType="board"> SELECT * FROM board
<where> <if test="search != null || search =='' "> subject LIKE #{search} </if> </where> ORDER BY re_ref DESC, re_seq ASC OFFSET #{startRow} LIMIT #{pageSize} </select>
<update id="updateGroupSeq" parameterType="board"> UPDATE board SET re_seq = re_seq + 1 WHERE re_ref = #{re_ref} AND re_seq > #{re_seq} </update> </mapper> |
#3 boardMyBatisDao.java
package dao;
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map;
import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import vo.Board;
public class boardMyBatisDao { SqlSessionFactory factory; private String NAMESPACE ="dao.mapper.BoardMapper.";
private SqlSessionFactory getSqlSessionFactory() { if(factory !=null) { // 페이지가 변경될때마다 설정파일을 불러오는 작업을 하지않기 위해 선언 return factory; } InputStream is = null; try { is = Resources.getResourceAsStream("mybatis-config.xml"); // 설정파일 불러오기 } catch (IOException e) { e.printStackTrace(); } SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); // 설정파일을 읽기 위한 객체 factory= builder.build(is); return factory; }//getSqlSessionFactory
// 1) INSERT 메소드 -> 두 개 이상의 sql 사용하기 public int insertBoard(Board board) { // sqlSession 생성 -> DB 연결 // mybatis는 수동커밋이므로 sqlSession.commit();을 사용하지않는다면 // openSession()을 true로 바꿔준다. SqlSession sqlSession= getSqlSessionFactory().openSession(true);
// SELECT 문 사용 : sql 리턴 값이 null(레코드값이 없을경우) 일 수도 있기 때문에 Integer를 사용 Integer num = sqlSession.selectOne(NAMESPACE+"getMaxBoardNum"); if(num == null) { num = 1; }else { num +=1; } // 직접입력정보 board.setNum(num); board.setRe_ref(num); board.setRe_lev(0); board.setRe_seq(0); board.setReadcount(0);
// INSERT 문 사용 int rowCount = sqlSession.insert(NAMESPACE+"insertBoard",board); sqlSession.close(); return rowCount; }//insert
// 2) 여러 가지 변수 사용하기 public List<Board> getBoards(int startRow, int pageSize, String search){ SqlSession sqlSession= getSqlSessionFactory().openSession();
// 2개 이상의 변수를 맵으로 전달 Map<String, Object> map = new HashMap<String, Object>(); map.put("startRow", startRow); map.put("pageSize", pageSize); map.put("search", "%"+search+"%");
List<Board> list = sqlSession.selectList(NAMESPACE+"getBoards", map); sqlSession.close(); return list; }//getBoards
// 3) sql문 2개이상 사용하기 public void replyInsert(Board board) { SqlSession sqlSession= getSqlSessionFactory().openSession(false);
String statement = NAMESPACE +"pdateGroupSeq"; sqlSession.update(statement, board);
statement = NAMESPACE+"getMaxBoardNum"; Integer num = sqlSession.selectOne(statement); if(num != null) { num = num+1; } // 답글정보 board.setNum(num); board.setRe_lev(board.getRe_lev()+1); board.setRe_seq(board.getRe_seq()+1); board.setReadcount(0);
statement = NAMESPACE+"insertBoard"; int result = sqlSession.insert(statement, board); if(result>0) { sqlSession.commit(); }
sqlSession.close(); }//replyInsert
public static void main(String[] args) { boardMyBatisDao dao = new boardMyBatisDao();
// insertBoard 메소드 테스트 Board board1 = new Board(); board1.setName("Mybatis1"); board1.setPass("1234"); board1.setSubject("Mybatis1"); board1.setContent("Mybatis1"); // dao.insertBoard(board1);
System.out.println("======================");
// getBoards 메소드 테스트 List<Board> list = dao.getBoards(0, 5, "답글"); for(Board board : list) { System.out.println(board); }; }//main
}//boardMyBatisDao |
'Mybatis' 카테고리의 다른 글
Mybatis#4) 복합 SQL (0) | 2019.04.18 |
---|---|
Mybatis#2 : 예제(insert, update, select, delete..) (1) | 2019.04.16 |
MyBatis 사용하기 : DB연결 (0) | 2019.04.16 |