●MyBatis - SQL Mapping Framework for Java
java에서 xml파일을 접근해야함(mapping) sql분리하기(유지보수 용이함)
*Java에서 xml로 되어있는파일(mapper file)에 sql을 쓰고싶으면 id이름을 찾아가서
xml로 뺄수있음.
MyBatis내부에 JDBC를 쓰는것이라 JDBC API도 필요하다
MyBatis환경설정
The configuration XML file - 환경설정파일
SQL만 모아져있는파일 - mapper파일
database접근정보 알려줘야함?
core of the MyBatis system core파일
xml파일로
<configuration>
<environments>
JDBC에 연결할수있도록~~~~
SQL에있는 xml파일을 mappers로 연결
●환경설정파일(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>
<properties resource="kr/smhrd/mybatis/db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="kr/smhrd/mybatis/MemberMapper.xml"/>
</mappers>
</configuration>
SqlSessionFactory 안에 SqlSession들
★ConnectionPool - Sql세션들 (connection객체들)을 모아둔 pool을미리만들어놓고 필요할때마다 db에서재활용
(MyBatis는 이미 만들어져있음)
●mapper.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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
EL - ${ }
jQuery - $( )
MyBatis - #{ }
●db.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:XE
username=hr
password=hr
●MemberDAOImpl
// 초기화 블럭(한번만 실행하는 블럭)
static {
String resource = "kr/smhrd/mybatis/config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
}
InputStream - 입력스트림(입력하는 빨대) <-> Resources.get xml파일
SqlSessionFactoryBuilder().build(inputStream) - xml읽어서 build메소드로 Connection통해 만들기
▼예외처리 해주기
private static SqlSessionFactory sqlSessionFactory;
// 초기화 블럭(한번만 실행하는 블럭)
static {
String resource = "kr/smhrd/mybatis/config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
inputStream에 예외처리도 해줘야하고,
try문안에 SqlSessionFactory가있으면 뭔가가 안돼서 try문 밖에서 private static으로 선언해준다.
●MemberDAOImpl
@Override
public List<MemberVO> memberList() {
SqlSession session = sqlSessionFactory.openSession();
//SQL문장(select ~,...) + MemberVO + ArrayList(X, - selectList())
List<MemberVO> list = session.selectList("memberList");
session.close();
return list;
}
get과같은게 openSession
openSession했으면 session.close(반납개념)해야함.
●MemberMapper.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="kr.smhrd.mybatis.MemberMapper">
<select id="memberList" resultType="MemberVO">
select * from memiot
</select>
</mapper>
위에서 말했듯이 mapper file에 sql을 쓰고싶으면 id이름을 찾아가서 xml로 뺄수있다.
●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>
<properties resource="kr/smhrd/mybatis/db.properties"/>
<typeAliases>
<typeAlias type="kr.smhrd.model.MemberVO" alias="MemberVO"/>
</typeAliases>
MemberMapper.xml에서 alias쓸려면 config(환경설정)에서 alias 설정해주면 된다.
● MemberDAOImpl.java (최종)
//myBatis
public class MemberDAOImpl implements MemberDAO{
private static SqlSessionFactory sqlSessionFactory;
// 초기화 블럭(한번만 실행하는 블럭)
static {
String resource = "kr/smhrd/mybatis/config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<MemberVO> memberList() {
SqlSession session = sqlSessionFactory.openSession();
//SQL문장(select ~,...) + MemberVO + ArrayList(X, - selectList())
List<MemberVO> list = session.selectList("memberList");
session.close();
return list;
}
@Override
public int memberInsert(MemberVO vo) {
SqlSession session = sqlSessionFactory.openSession();
int cnt = session.insert("memberInsert",vo);
session.commit(); //완료
session.close(); //반납
return cnt;
}
@Override
public int memberDelete(int num) {
SqlSession session = sqlSessionFactory.openSession();
int cnt = session.delete("memberDelete",num);
session.commit(); //완료
session.close(); //반납
return cnt;
}
@Override
public MemberVO memberContent(int num) {
SqlSession session = sqlSessionFactory.openSession();
MemberVO vo = session.selectOne("memberContent",num);
session.close(); //반납
return vo;
}
@Override
public int memberUpdate(MemberVO vo) {
SqlSession session = sqlSessionFactory.openSession();
int cnt = session.update("memberUpdate",vo);
session.commit(); //완료
session.close(); //반납
return cnt;
}
}
insert는 select와달리 DB의 값을 변경하기 때문에 session.commit을 추가로 해줘야함
delete도 commit해야하지만 int num으로
content도 num을 받고 commit은 사용하지않아도된다.
update는 commit해야하고 MemberVO vo로 받아온다
● MemberMapper.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="kr.smhrd.mybatis.MemberMapper">
<select id="memberList" resultType="MemberVO">
select * from memiot
</select>
<insert id="memberInsert" parameterType="MemberVO">
insert into memiot values(num_seq.nextval,
#{id},
#{pass},
#{mname},
#{mage},
#{memail},
#{mtel})
</insert>
<delete id="memberDelete" parameterType="Integer">
delete from memiot where num=#{num}
</delete>
<select id="memberContent" parameterType="Integer" resultType="MemberVO">
select * from memiot where num=#{num}
</select>
<update id="memberUpdate" parameterType="MemberVO" >
UPDATE memiot SET mage=#{mage}, memail=#{memail}, mtel=#{mtel} WHERE num=#{num}
</update>
</mapper>
MemberDAOImpl.java (최종) 에 맞게 sql문을 mybatis #{ }이용해 사용하고
각 id , parameterType , resultType 를 잘 성정해야한다.
'JSP Servlet' 카테고리의 다른 글
JSP 내장 객체 (0) | 2023.09.22 |
---|---|
회원인증 (0) | 2021.02.16 |
비동기식페이지2(JSON , Ajax) (0) | 2021.02.08 |
비동기식페이지(JQuery,Ajax,JSON) (0) | 2021.02.08 |
회원관리 MVC2+HandlerMapping+JSTL (0) | 2021.02.08 |