1. 程式人生 > >mybatis---Dao開發模式

mybatis---Dao開發模式

UserDao介面:

package com.it.mybaties.dao;

import com.it.mybaties.pojo.User;

public interface UserDao {
	public User selectUser(Integer id);
}

UserDaoImpl(UserDao的實現類):

package com.it.mybaties.dao;

import java.io.IOException;
import java.io.InputStream;

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 com.it.mybaties.pojo.User;

public class UserDaoImpl implements UserDao {
	
	private SqlSessionFactory sqlSessionFactory;
	
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	public User selectUser(Integer id){
		SqlSession openSession = sqlSessionFactory.openSession();
		User user = openSession.selectOne("test.getUserById", id);
		
		return user;
		
	}
	
}

Test(junit測試):

package com.it.mybaties.junit;

import java.io.IOException;
import java.io.InputStream;

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 org.junit.Test;

import com.it.mybaties.dao.UserDao;
import com.it.mybaties.dao.UserDaoImpl;
import com.it.mybaties.pojo.User;

public class TestMybatisDao {
	
	@Test
	public void fun2() throws Exception{
		String resource = "sqlMapperConfig.xml";
		InputStream in = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory =
                     new SqlSessionFactoryBuilder().build(in);
		
		UserDao userdao = new UserDaoImpl(sqlSessionFactory);
		User user = userdao.selectUser(37);
		System.out.println(user);
		
	}
}