1. 程式人生 > >mybatis開發原始dao的方式

mybatis開發原始dao的方式


1定義介面UserDao

package cn.itcast.dao;

import java.util.List;

import cn.itcast.po.User;

public interface UserDao {
	//根據使用者ID查詢使用者資訊 
	public User findUserById(int id)  throws Exception;
	//根據使用者名稱稱模糊查詢使用者列表 
	public List<User> findUserByName(String name);
	//新增使用者 
	public void insertUser(User user);
}


2寫UserDaoImpl實現類

package cn.itcast.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.itcast.po.User;

public class UserDaoImpl implements UserDao {
	//依賴注入
	private SqlSessionFactory sqlSessionFactory ;
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory ;
	}
	@Override
	public User findUserById(int id) throws Exception {
		
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//呼叫SqlSession的增刪改查
		User user = sqlSession.selectOne("test.findUserById", id);
		//關閉資源
		sqlSession.close();
		return user;
	}
	@Override
	public List<User> findUserByName(String name) {
		//建立SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//呼叫SqlSession的增刪改查
		List<User>list = sqlSession.selectList("test.findUserByName", name);
		//關閉資源
		sqlSession.close();
		return list;
	}

	@Override
	public void insertUser(User user) {
		// TODO Auto-generated method stub

	}

}


3測試程式碼

package cn.itcast.dao;

import static org.junit.Assert.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import cn.itcast.po.User;

public class UserDaoTest {
	private SqlSessionFactory sqlSessionFactory;
	@Before
	public void setUp() throws Exception {
		//讀取配置檔案
		String resource ="SqlMapConfig.xml";
		InputStream inputStream =  Resources.getResourceAsStream(resource);
		//建立SqlSessionFactory
		 sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);	

	}
	
	@Test
	public void testFindUserById() throws Exception {
		
		//建立UserDao
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		User user = userDao.findUserById(1);
		System.out.println(user);		
	}

	@Test
	public void testFindUserByName() throws Exception {
		//讀取配置檔案
		String resource ="SqlMapConfig.xml";
		InputStream inputStream =  Resources.getResourceAsStream(resource);
		//建立SqlSessionFactory
	    sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
		UserDao userDao = new UserDaoImpl(sqlSessionFactory);
		List<User> list = userDao.findUserByName("%小明%");
		System.out.println(list);	
	}

	@Test
	public void testInsertUser() {
		fail("Not yet implemented");
	}

}