카테고리 없음

mapper namespace에 관하여

prden 2021. 6. 7. 21:04

1. 언제 namespace에 명확하게 인터페이스 명을 구체적으로 패키지까지 다 명시해주어야 하는가?

1) root-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
          xmlns:tx="http://www.springframework.org/schema/tx"
          xmlns:context="http://www.springframework.org/schema/context"
          xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context 
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx 
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

       <!-- web.xml에 정의된 ConterxtLoaderListener가 로딩하는
                자바빈(부모컨텍스트)을 정의
            DispatcherServlet이 로딩하는 자바빈은 자식 컨텍스트임 -->

       <context:property-placeholder location="classpath:jdbc.properties" />

       <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
             <property name="driverClassName" value="${jdbc.driverClassName}" />
             <property name="url" value="${jdbc.url}" />
             <property name="username" value="${jdbc.username}" />
             <property name="password" value="${jdbc.password}" />
       </bean>

       <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
             <property name="dataSource" ref="dataSource" />
             <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
             <property name="mapperLocations" value="classpath:/mybatis/mapper/**/*.xml" />
             <property name="typeAliases">
              <list>
              <value>com.legalcounsel.javaprj.model.Auth</value> 
              <value>com.legalcounsel.javaprj.model.Board</value>
              <value>com.legalcounsel.javaprj.model.BoardComment</value>
              <value>com.legalcounsel.javaprj.model.CommentProfile</value>
              <value>com.legalcounsel.javaprj.model.User</value>
              <value>com.legalcounsel.javaprj.model.BoardReplyVo</value>
              <value>com.legalcounsel.javaprj.model.FileVO</value>
              
             
              </list>
             </property>
       </bean>
          
   
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage"
             value="com.legalcounsel.javaprj.repository2" />
       </bean>
 
		<bean id ="userDetailsDao" class="com.legalcounsel.javaprj.repository.UserDetailDaoImpl">
		<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
		</bean>
       <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"
             destroy-method="clearCache">
             <constructor-arg name="sqlSessionFactory" ref="SqlSessionFactory" />
       </bean>
       
       <bean id="transactionManager"
             class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
             <property name="dataSource" ref="dataSource" />
       </bean>
       <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

2) 인터페이스와 그 구현 클래스

package com.legalcounsel.javaprj.repository;

import com.legalcounsel.javaprj.model.User;

public interface UserDetailsDao {

	public User findUserByUsername(String uname);
	
	public void insertLogIn(String uname);
	
	public void insertLogOut(String uname);
	
    
}


package com.legalcounsel.javaprj.repository;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import com.legalcounsel.javaprj.model.User;


@Repository("UserDetailsDao")
public class UserDetailDaoImpl implements UserDetailsDao {

	private SqlSessionTemplate sqlSessionTemplate;

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	
	@Override
	public User findUserByUsername(String uname) {
//동적 쿼리 만드는 방법 알아야 될 듯 -> selectOne으로 여러 번 쿼리 날려서 담아올 수 있게 
		User user =  sqlSessionTemplate
				.selectOne("com.legalcounsel.javaprj.repository.UserDetailsDao.findUserByUsername", uname);

		return user;
	}

	@Override
	public void insertLogIn(String uname) {
		sqlSessionTemplate.insert("com.legalcounsel.javaprj.repository.UserDetailsDao.insertLogIn", uname);
	}

	@Override
	public void insertLogOut(String uname) {
		sqlSessionTemplate.insert("com.legalcounsel.javaprj.repository.UserDetailsDao.insertLogOut", uname);

	}

3)**-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="com.legalcounsel.javaprj.repository.UserDetailsDao">

	 <resultMap id="userResult" type="user">
		<id column="uname" jdbcType="VARCHAR" property="uname" />
		<result property="pwd" jdbcType="VARCHAR" column="pwd" />
		<result property="enabled" jdbcType="TINYINT" column="enabled" />
		<collection property="auths" column ="uname" javaType="ArrayList" ofType="auth">
			<id property="uname" column="uname" />
			<result property="role" column="role" />
		</collection>
	</resultMap>
	
	<select id="findUserByUsername" parameterType="string" resultMap="userResult">
		SELECT u.uname, u.pwd, u.enabled, r.uname, r.role FROM user u LEFT JOIN auth r ON (u.uname = r.uname) WHERE u.uname=#{value}; 
	</select>
	
	<insert id="insertLogIn" parameterType="String">
    	INSERT INTO LOGINHISTORY (UNAME, LTYPE, LDATE)
    	 	              VALUES (#{uname}, 'I', NOW() );
    </insert>

    <insert id="insertLogOut" parameterType="String">
    	INSERT INTO LOGINHISTORY (UNAME, LTYPE, LDATE)
    	 	              VALUES (#{uname}, 'O', NOW() );
    </insert>
	
	
</mapper>

2. namespace에 명확하게 인터페이스 명 명시하지 않아도 되는 경우

 1) applicationContext.xml에 다음과 같이 명시

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-4.3.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
             http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

    <!-- web.xml에 정의된 ConterxtLoaderListener가 로딩하는 자바빈(부모컨텍스트)을 정의
                DispatcherServlet(servlet-context.xml)이 로딩하는 자바빈은 자식 컨텍스트임 -->

    <context:property-placeholder location="classpath:jdbc.properties" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/Mybatis/mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:/Mybatis/Sql/**-mapper.xml" />
        <property name="typeAliases">
            <list>
                <value>com.legalcounsel.User.Register.UserDTO</value>
<!--                <value>com.legalcounsel.javaprj.model.Board</value>-->
<!--                <value>com.legalcounsel.javaprj.model.BoardComment</value>-->
<!--                <value>com.legalcounsel.javaprj.model.CommentProfile</value>-->
<!--                <value>com.legalcounsel.javaprj.model.User</value>-->
<!--                <value>com.legalcounsel.javaprj.model.BoardReplyVo</value>-->
<!--                <value>com.legalcounsel.javaprj.model.FileVO</value>-->
            </list>
        </property>
    </bean>

    <!--트랜젝션 관리자 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
        <constructor-arg name="sqlSessionFactory" ref="SqlSessionFactory" />
    </bean>

 

2) 인터페이스 및 구현 클래스

package com.legalcounsel.User.Register;


public interface UserRegDao {
    public UserDTO selectByEmail(String email);
    public void insertUser(UserDTO newUser);

}


package com.legalcounsel.User.Register;


import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("UserRegDao")
public class UserRegDaoImpl implements UserRegDao{

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public UserDTO selectByEmail(String email) {
        return sqlSessionTemplate.selectOne("selectByEmail", email);
    }

    @Override
    public void insertUser(UserDTO newUser) {
        sqlSessionTemplate.insert("insertUser", newUser);

    }

}

 

3) user-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="UserRegDao">
    <select id="selectByEmail" parameterType="String" resultType="userDTO">
        SELECT * FROM USER WHERE EMAIL=#{email}
    </select>

    <insert id="insertUser" parameterType="userDTO">
        INSERT INTO USER (USERNAME, EMAIL, PASSWORD )VALUES (#{username}, #{email}, #{password})
    </insert>
</mapper>