Mybatis#2 : 예제(insert, update, select, delete..)

2019. 4. 16. 13:01Mybatis

*** 작동방식

#1 mybaits-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>

<typeAlias alias="member" type="vo.Member"/>

</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"/>

</mappers>

</configuration>

#2 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="dao.mapper.MemberMapper">

 

 

<select id="getMemberById" parameterType="string" resultType="member">

select id as id

from member

where id = #{id}

</select>

 

<select id="getAllMembers" resultType="member">

SELECT * FROM member ORDER BY id

</select>

 

<select id="countById" parameterType="String" resultType="int">

SELECT COUNT(*)

FROM member

WHERE id = #{id}

</select>

 

<select id="loginCheck" parameterType="string" resultType="string">

SELECT password

FROM member

WHERE id = #{id}

</select>

 

 

<insert id="insertMember" parameterType="member">

INSERT INTO member (id,password,name,birthday,gender,email,address,tel,mtel,reg_date)

VALUES (#{id}, #{password}, #{name}, #{birthday}, #{gender}, #{email}, #{address}, #{tel}, #{mtel}, CURRENT_TIMESTAMP )

</insert>

 

<delete id="deleteAllMembers">

 

TRUNCATE TABLE member

</delete>

 

 

<delete id="deleteMember" parameterType="String">

DELETE FROM member

WHERE id = #{id}

</delete>

 

 

<update id="updateM" parameterType="member">

UPDATE member

SET pasword =#{passward}, name = #{name}

WHERE id = #{id}

</update>

</mapper>

 

#3 MemberMyBatisDao.java 

package dao;

 

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

 

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.Member;

 

public class MemberMyBatisDao {

 

SqlSessionFactory factory;

private String NAMESPACE ="dao.mapper.MemberMapper.";

 

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

 

public Member getMemberById(String id) {

// SqlSession 선언 => 기존의 Connection과 동일

SqlSession sqlSession= getSqlSessionFactory().openSession();

 

// 현재 버전에서는 다운캐스팅을 안해줘도 상관없다.

Member member = (Member)sqlSession.selectOne(NAMESPACE+"getMemberById",id); // id에 해당하는 레코드값을 가져온다 , 한개의 레코드값

sqlSession.close();

return member;

}//getMemberById

 

public List<Member> getAllMembers(){

SqlSession sqlSession = getSqlSessionFactory().openSession();

List<Member> list =(List)sqlSession.selectList(NAMESPACE+"getAllMembers");

sqlSession.close();

return list;

}//getAllMembers()

 

public int insertMember(Member member) {

SqlSession sqlSession = getSqlSessionFactory().openSession();

int suc = sqlSession.insert(NAMESPACE+"insertMember", member);

if(suc >0) {

sqlSession.commit(); // mybatis는 수동 커밋이므로 확인작업

}else {

sqlSession.rollback();

}

sqlSession.close();

return suc;

}//insertMember

 

public int deleteAllMembers() {

SqlSession sqlSession = getSqlSessionFactory().openSession();

int suc = sqlSession.delete(NAMESPACE+"deleteAllMembers");

if(suc >0 ) {

sqlSession.commit();

}else {

sqlSession.rollback();

}

sqlSession.close();

return suc;

}// deleteAllMembers

 

public int deleteMember() {

SqlSession sqlSession = getSqlSessionFactory().openSession();

int suc = sqlSession.delete(NAMESPACE+"deleteMember");

if(suc >0 ) {

sqlSession.commit();

}else {

sqlSession.rollback();

}

sqlSession.close();

return suc;

}//deleteMember

 

public int updateMember(Member member) {

SqlSession sqlSession = getSqlSessionFactory().openSession();

int suc = sqlSession.update(NAMESPACE+"updateMember",member);

if(suc >0 ) {

sqlSession.commit();

}else {

sqlSession.rollback();

}

sqlSession.close();

return suc;

}//updateMember

 

public int countById(String id) {

SqlSession sqlSession = getSqlSessionFactory().openSession(true);

int count = sqlSession.selectOne(NAMESPACE+"countById", id);

sqlSession.close();

return count;

}//countById

 

public int loginCheck(String id, String pass) {

int check = -1;

String password = "";

SqlSession sqlSession = getSqlSessionFactory().openSession();

try {

// 예외 발생시 null이 발생

password = sqlSession.selectOne(NAMESPACE+"loginCheck", id);

} catch (Exception e) {

e.printStackTrace();

check = -1; // 아이디 없음

}finally {

sqlSession.close();

}

 

if(password.equals(pass)) {

check = 1;// 비밀번호 일치

}else {

check =0; // 비밀번호 불일치

}

return check;

 

}//loginCheck

 

// 실행 테스트

public static void main(String[] args) {

// 테스트

MemberMyBatisDao dao = new MemberMyBatisDao();

 

// Member member = dao.getMemberById("admin");

 

 

// List list = dao.getAllMembers();

// for(Member member1 : list) {

// System.out.println(member1);

// }

 

int suc = dao.loginCheck("admin","1324");

System.out.println(suc);

 

 

}//main

}// MemberMyBatisDao

'Mybatis' 카테고리의 다른 글

Mybatis#4) 복합 SQL  (0) 2019.04.18
Mybatis#3) 예제 : 복수변수 ,Map변수  (0) 2019.04.17
MyBatis 사용하기 : DB연결  (0) 2019.04.16