kys96811
483
2017-02-13 11:14:03
8
4965

Mybatis SqlSession null 에러......


안녕하세요? ibatis를 쓰다가 mybatis로 쓰려고하는데

설정이 뭐가 잘못되었는지 계속 sqlsession이 null로 떨어지네요..

해결책을 알려주시면 감사하겠습니다.


DTO와 UserMapper로 도메인을 사용하고 있구요.

SqlMapUserDAO에서 SqlSession을 통해 DB에서 가져오려고 합니다.


먼저, application-context.xml 설정은 다음과 같습니다.

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

	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!-- <bean id=“dataSource” class=“org.springframework.jndi.JndiObjectFactoryBean”>
        <property name=“jndiName” value=“java:/comp/env/jdbc/SpringDS” />
    </bean> -->
	
	<context:component-scan base-package="com.etmf.user.dao" />
	
	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
	    <property name="jndiName" value="java:comp/env/jdbc/SpringDS"/>
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.etmf.user.dto"/>
        <property name="configLocation" value="/WEB-INF/spring/mybatis-config.xml" />
    </bean>
    
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    


다음으로, mybatis-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>

	<settings>
		<setting name="cacheEnabled" value="false"/>
		<setting name="useGeneratedKeys" value="true"/>
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="defaultExecutorType" value="BATCH"/>
		<setting name="defaultStatementTimeout" value="3000"/>
	</settings>
	
	<mappers>
	  <mapper resource="../mybatis-query/user.xml"/>       
	</mappers>
	
</configuration>


다음으로, UserDAO는 다음과 같습니다.

package com.etmf.user.dao;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import com.etmf.user.dto.UserDTO;

@Repository("UserDAO")
public interface UserDAO {

	// 유저 전체 검색
	public List<UserDTO> getUserList();
	
	// 유저 id 검색
	public UserDTO getUserById(@PathVariable("id") int id);
	
	// 유저 생성
	public int addUser(@RequestBody UserDTO user);
	
	// 유저 정보 업데이트
	public int updateUser(@RequestBody UserDTO user);
	
	// 유저 삭제
	public void deleteUser(@PathVariable("id") int id);
	
}


다음으로, SqlMapUserDAO는 다음과 같습니다.

package com.etmf.user.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
/*import org.apache.log4j.Logger;*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import com.etmf.user.dto.UserDTO;

@Transactional
@Repository("UserDAO")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SqlMapUserDAO implements UserDAO {
	
	@Qualifier("sqlSessionFactory")
    private SqlSession sqlSession;
	
	public void setSqlSession(SqlSession sqlSession){
        this.sqlSession = sqlSession;
    }
	
	/*protected final Logger logger = Logger.getLogger(getClass());*/
	
	// 유저 전체 검색
	public List<UserDTO> getUserList() throws DataAccessException{
		
		try{
			
			System.out.println("SqlSession ===> " + sqlSession);
			
			List<UserDTO> userDtoList = sqlSession.selectList("user.getUserList");
			
			return userDtoList;
			
		}catch(Exception e){
			
			e.printStackTrace();
			
			return null;
			
		}
		
	}


그랬을 때, 다음과 같이 SqlSession이 null이 계속 발생하는데요. 어디가 잘못된 건가요? ㅠㅠ

SqlSession ===> null


알려주시면 감사하겠습니다.


jndi 방식으로 server.xml에서 설정으로 사용하고 있습니다.

<GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    
        <!-- jndi 설정 -->    
        <Resource name="jdbc/SpringDS" 
        	auth="Container"
        	type="javax.sql.DataSource" 
        	driverClassName="com.mysql.jdbc.Driver"
        	factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            url="jdbc:mysql://localhost:3307/etmf" 
            username="root" 
            password="****" 
            maxActive="100" 
            maxIdle="10" 
            maxWait="10000"
            initialSize="10"
            validationQuery="SELECT 1 FROM DUAL"
            defaultAutoCommit="false"
            />
            
  </GlobalNamingResources>


감사합니다.


0
0
  • 답변 8

  • 으어어어어
    641
    2017-02-13 11:33:26 작성 2017-02-13 11:34:17 수정됨
    private SqlSession sqlSession;

    위에 

    @Autowired 혹은 @Resource(name = "sqlSession") 을 적으셔도 안되나요?

    @Autowired
    private SqlSession sqlSession;
    
    @Resource(name = "sqlSession")
    private SqlSession sqlSession;

    이런식으로..


    0
  • kys96811
    483
    2017-02-13 11:51:44

    네~ sqlSession 에 autowired 붙이면

    2월 13, 2017 11:50:47 오전 org.apache.catalina.core.StandardContext listenerStart
    심각: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UserDAO': Unsatisfied dependency expressed through field 'sqlSession'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.ibatis.session.SqlSession' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    	at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3782)
    	at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    	at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5545)
    	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1388)
    	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1392)
    	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1392)
    	at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1360)
    	at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.ibatis.session.SqlSession' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    	... 26 more

    이런 에러가 떨어집니다..

    0
  • 으어어어어
    641
    2017-02-13 12:31:55

    @autowired를 사용하실 거면

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

    이 부분을

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">

    이렇게 바꿔 주시고요

    @resource를 사용하실려면


    @Resource(name = "sqlSessionFactory")

    로 사용해주세요

    0
  • kys96811
    483
    2017-02-13 13:18:26

    위처럼 사용했는데도 계속 같은 에러가 뜨네요.. bean id도 같게 해줬는데 뭐가 문제일까요?

    0
  • 으어어어어
    641
    2017-02-13 13:31:03
    혹시 sqlsession에 sqlsessionfactory를 인젝션 받으니 타입이 안맞아서 그런걸까요...
    0
  • kys96811
    483
    2017-02-13 13:38:02

    글쎄요 그건 아닌거같은데 ㅠㅠ 지금 코드를 조금 수정해서 이렇게 되었거든요

    SqlMapUserDAO.java는

    @Transactional
    @Repository("UserDAO")
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public class SqlMapUserDAO implements UserDAO {
    	
    	@Autowired
        private SqlSession sqlSession;
    	
    	public void setSqlSession(SqlSession sqlSession){
            this.sqlSession = sqlSession;
        }
    	
    	/*protected final Logger logger = Logger.getLogger(getClass());*/
    	
    	// 유저 전체 검색
    	public List<UserDTO> getUserList() throws DataAccessException{
    		
    		
    		/*SqlSession session = SqlMapSessionFactory.openSession();*/
    		
    		try{
    			
    			System.out.println("SqlSession ===> " + sqlSession);
    			
    			List<UserDTO> userDtoList = sqlSession.selectList("user.getUserList");
    			
    			return userDtoList;


    xml 설정은

    
    	<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    	    <property name="jndiName" value="java:comp/env/jdbc/SpringDS"/>
    	</bean>
    
    	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- <property name="typeAliasesPackage" value="com.crscube.etmf.user"/> -->
            <property name="configLocation" value="/WEB-INF/spring/mybatis-config.xml" />
        </bean>
        
        <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>


    이렇게 해도 계속 이 에러가 뜨네요 ㅜ

    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UserDAO': Unsatisfied dependency expressed through field 'sqlSession'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.ibatis.session.SqlSession' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4727)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
    	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
    	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    	at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
    	at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1805)
    	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    	at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.ibatis.session.SqlSession' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    	... 28 more



    0
  • 으어어어어
    641
    2017-02-13 14:19:37

    혹시 service에서 sqlmapuserdao를 어떻게 부르시나요?

    0
  • joonYi
    30
    2018-02-24 18:43:57
    혹시 이문제 해결 하셨나요 ??
    0
  • 로그인을 하시면 답변을 등록할 수 있습니다.