728x90

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="com.mybatis3.dao.mapper.StudentMapper">

         <resultMap id="studentResultMap" type="com.mybatis3.domain.Student">    

         <select id="findStudentByIdMap">

</mapper>

mapper의 namespace = "mapper의 위치"

 

<resultMap>

type: DB로 부터 받은 데이터 result를 바인딩할 java의 클래스 

<resultMap id="studentResultMap" type="com.mybatis3.domain.Student">

<id column="STUD_ID" property="studId"/>

<result column="NAME" property="name"/>

<result column="EMAIL" property="email"/>

<result column="DOB" property="dob"/>

</resultMap>

id = primaryKey

result = 나머지

column="데이터베이스의 컬럼명"

property="자바 클래스의 변수명" 

 

<resultMap id="studentWithAddressResultMap" type="com.mybatis3.domain.Student" autoMapping="true">

autoMapping = id, result를 직접 바인딩하지 않아도 column과 property를 비교하여 알아서 바인딩 해준다. 

다만, 하나의 클래스가 다른 클래스를 포함하고 있거나 컬렉션으로 갖는 경우 

id는 직접 기술해주어야하며, 

포함하고 있는 다른 클래스에 동일한 변수명을 가진 property가 있다면 또한 명시해주어야 한다. 

 

하나의 클래스가 다른 클래스를 포함하고 있는 경우 

<resultMap id="studentWithAddressResultMap" type="com.mybatis3.domain.Student" autoMapping="true">

<id column="STUD_ID" property="studId"/>

<association property="address" javaType="com.mybatis3.domain.Address" autoMapping="true">

<id column="ADDR_ID" property="addrId"/>

</association>

</resultMap>

<association> javaType="포함되는 클래스"

 

하나의 클래스가 다른 컬렉션을 포함하고 있는 경우

<resultMap id="studentWithCoursesResultMap" type="com.mybatis3.domain.Student" autoMapping="true">

<id column="STUD_ID" property="studId"/>

<result column="STUDENT_NAME" property="name"/>

<collection property="courseList" ofType="com.mybatis3.domain.Course" autoMapping="true">

<id column="COURSE_ID" property="courseId"/>

<result column="COURSE_NAME" property="name"/>

</collection>

</resultMap>

 

<collection> ofType="포함되는 컬렉션의 클래스"

동일한 프로퍼티를 가진 경우, <result>로 따로 맵핑해준다.

 

sql문도 작성 가능

<insert id="insertStudentBySequenceReturnPrimaryKey" parameterType="com.mybatis3.domain.Student">

<selectKey keyProperty="studId" order="BEFORE" resultType="int">select students_stud_id_seq.nextval from dual</selectKey>

insert into students(stud_id,name,email,dob) values(#{studId},#{name},#{email},#{dob})

</insert>

parameterType="insert시 필요한 파라메터의 타입"

<selectKey> insert시 sequence를 사용하여 pk를 초기화한다면 

insert후 insert한 데이터의 pk를 바로 반환 받기 위해 사용 

select students_stud_id_seq.nextval from dual

seq.nextval로 다음 seq 값을 미리 알아낸 후 

insert 할때는 seq.currval 값으로 insert 한다. 

파라메터를 넣을 땐 #{...property...} 표현식을 사용한다.

 

mybatis 사용

* 0. mybatis-config.xml --> InputStream

InputStream myBatisConfigInputStream = Resources.getResourceAsStream("mybatis-config.xml");

* 1. SqlSessionFactoryBuilder

SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();

* 2. SqlSessionFactory

SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(myBatisConfigInputStream);

* 3. SqlSession open (Connection) autocommit true

SqlSession sqlSession=sqlSessionFactory.openSession(true);

* 4. SqlSession사용(CRUD)

//List<Student> studentList=sqlSession.selectList("com.mybatis3.dao.mapper.StudentBasicMapper.findAllStudents");

Student student=sqlSession.selectOne(

"com.mybatis3.dao.mapper.StudentBasicMapper.findStudentById",1);

* 5. SqlSession close

sqlSession.close();

sqlSessionFactory.open(autocommit true?)

 

sqlSession 메소드

selectOne()  객체 한개 반환 받을 때 

selectList() 객체 컬렉션을 반환 받을 때

insert(), update(), delete()

 

sqlSession.method(namespace+sql태그 id, 파라메터)

 

 

 

 

 

interface 에서 설정

-인터페이스의 풀네임은 Mapper.xml의 namespace와 일치

-메소드 이름은 Mapper.xml의 id와 일치

-메소드 인자타입은 Mapper.xml의 parameterType과 일치

-메소드 리턴타입은 Mapper.xml의 resultType과 일치 

 

@Select("select stud_id as studid,name,email,dob from students where stud_id = #{studId}")

public Student findStudentById(@Param("studId")Integer studId);

어노테이션으로 sql문을 .xml 파일 대신 Mapper인터페이스에서 작성할 수 있다. 

 

 

Mapper interface 사용

* 0.mybatis-config-mapper-interface.xml --> InputStream

InputStream myBatisConfigInputStream = Resources.getResourceAsStream("mybatis-config-mapper-interface.xml");

* 1. SqlSessionFactoryBuilder

SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();

* 2. SqlSessionFactory

SqlSessionFactory sqlSessionFactory=

sqlSessionFactoryBuilder.build(myBatisConfigInputStream);

* 3. SqlSession open (Connection ) autocommit true

SqlSession sqlSession=sqlSessionFactory.openSession(true);

* 4. StudentMapper[MapperInterface]생성

* org.apache.ibatis.binding.MapperProxy

StudentBasicMapper studentBasicMapper

=sqlSession.getMapper(StudentBasicMapper.class);

* 4. StudentMapper[MapperInterface]사용(CRUD)

Student student = studentBasicMapper.findStudentByNo(1);

* 5. SqlSession close

sqlSession.close();

sqlSession을 얻는것까진 동일 

 

인터페이스는 직접 사용하지 못하고 인터페이스를 상속받아 구현한 클래스를 사용해야 한다. 

Mapper는 인터페이스이므로 Mapper를 구현한 클래스를 가져와야하는데 

sqlSession의 getMapper가 이러한 일을 대신해준다. 

이를 Proxy라고 한다. 

Mapper mapper = sqlSession.getMapper(Mapper.class);

mapper.메소드를 이용해 인터페이스에서 만든 메소드를 사용할 수 있다. 

 

 

Dao에서 Mapper 사용하기 예제

public class AddressDao {

private SqlSessionFactory sqlSessionFactory;

private static final String NAMESPACE ="com.mybatis3.dao.mapper.AddressMapper.";

public AddressDao() {

try {

InputStream myBatisConfigInputStream = Resources.getResourceAsStream("mybatis-config.xml");

SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

this.sqlSessionFactory = sqlSessionFactoryBuilder.build(myBatisConfigInputStream);

} catch (Exception e) {

e.printStackTrace();

}

}

sqlSession이 아닌 factory를 필드로 갖고 매번 factory에서 sqlSession을 가져다 쓰고 반납한다. 

Dao 생성자에서 sqlSessionFactory를 생성해준다.

 

public Address findAddressByIdWithStudents(Integer addrId) {

SqlSession sqlSession= sqlSessionFactory.openSession(true);

Address address=sqlSession.selectOne(NAMESPACE+"findAddressByIdWithStudents",addrId);

sqlSession.close();

return address;

}

'Web' 카테고리의 다른 글

YAML Converter  (0) 2023.10.11
SPA(single page application) Handlebars 활용하기  (1) 2023.09.21
HTML5 Basic  (0) 2023.09.19
MyBatis Config  (0) 2023.09.19
AJAX Asynchronous Javascript And XML  (0) 2023.09.18

+ Recent posts