mybatis-config.xml, xxxxx-mapper.xml 파일 생성을 완료하면
common 패키지를 만들어 싱글톤을 적용한 Template클래스를 만들고 SqlSession을 반환해주는 static메소드를 작성한다.
public static SqlSession getSqlSession() {
// mybatis-config 파일을 읽어서 해당 db와 연결된 sqlSession을 생성하여 반환
SqlSession sqlSession = null;
// SqlSession을 객체를 생성하기 위해서는 SqlSessionFactory 객체가 필요
// SqlSessionFactory 객체 생성을 위해서는 SqlSessionBuilder 객체가 필요
// /는 최상위 폴더를 의미한다.
String resource = "/mybatis-config.xml"; // mybatis-config 파일을 읽어야 하니 경로 설정.
try {
// 자원으로부터 Stream을 연다.
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
/*
* 순서
*
* 1. mybatis-config.xml 파일 경로 지정
* 2. inputStream 생성(config파일로부터 Stream을 얻어낸다.)
* 3. 얻어낸 Stream으로 builder를 이용하여 sessionFactory 객체 생성
* 4. 생성된 sessionFactory 객체로 sqlSession객체 생성.
*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sqlSession;
}
Service클래스에서 getSqlSession 메소드 호출을 통해 SqlSession을 생성
Dao클래스의 메소드 호출 시 전달 인자로 SqlSession 객체 전달
Dao클래스의 메소드에서 SqlSession 객체를 통해 쿼리에 접근
public Member loginMember(SqlSession sqlSession, Member m) {
Member loginUser = sqlSession.selectOne("memberMapper.selectMember", m);
return loginUser;
}