18.原始dao开发(和spring整合后)

1.mapper.xml

在config下新建sqlmap包,包中新建User.xml


User.xml

    

2. Sqlmapconfig中加载xml文件




    
    
        
        
        
    



3.DAO接口

DAO接口

4.DAO接口实现类

  • dao接口实现类需要注入SqlSessionFactory,通过spring进行注入。
    这里spring声明配置方式,配置dao的bean:
    在applicationContext.xml中配置

    
        
    
  • 让UserDaoImpl实现类继承SqlSessionDaoSupport
package com.chinglee.ssm.dao;

import com.chinglee.ssm.po.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
 * Created by Administrator on 2017/11/2 0002.
 */
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {

    @Override
    public User findUserById(int id) throws Exception {
       //继承SqlSessionDaoSupport,通过this.getSqlSession()得到sqlSession
        SqlSession sqlSession=this.getSqlSession();
        User user=sqlSession.selectOne("test.findUserById",id);
        return user;
    }
}

5.测试

package com.chinglee.ssm.dao;

import com.chinglee.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by Administrator on 2017/11/2 0002.
 */
public class UserDaoImplTest {
    private ApplicationContext applicationContext;
    //在setUp方法得到spring容器
    @Before
    public void setUp() throws Exception {
       applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }

    @Test
    public void findUserById() throws Exception {
         UserDao userDao= (UserDao) applicationContext.getBean("userDao");
         User user=userDao.findUserById(1);
         System.out.println(user);
    }

}

你可能感兴趣的:(18.原始dao开发(和spring整合后))