(Mybatis)整合后原生Dao的实现

整合的具体内容和步骤:请看上一篇

步骤一:在ApplicationContext.xml 配置文件中添加,

<!-- 配置原生Dao实现
注意: class必须指定Dao实现类的全路径名称
-->
<bean id="userDao" class="com.jadan.dao.UserDaoImpl">
	<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

步骤二:接口和实现类

     UserDao.java:

package com.jadan.dao;

import java.util.List;
import com.jadan.pojo.User;

public interface UserDao {
	// 通过id查用户
	public User findUserById(Integer id);
	
	// 通过用户名查询用户
	public List<User> findUserByUsername(String username);
	
	// 插入用户数据
	public void insertUser(User user);
	
	// 更改数据
	public void updateUserById(User user);
	
	// 删除数据
	public void delUserById(Integer id);
}

     UserDaoImpl.java:

package com.jadan.dao;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import com.jadan.pojo.User;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
	// 通过id查询用户
	public User findUserById(Integer id) {
		// sqlSession是线程不安全的,所以它的最佳使用范围在方法体内
		SqlSession openSession = this.getSqlSession();
		User user = openSession.selectOne("test.findUserById", id);
		// 整合后会话归spring管理,所以不需要手动关闭
//		openSession.close();
		return user;
	}

	// 通过用户名查询用户
	public List<User> findUserByUsername(String username) {
		SqlSession openSession = this.getSqlSession();
		List<User> list = openSession.selectList("test.findUserByUsername", username);
		return list;
	}

	// 插入用户数据
	public void insertUser(User user) {
		SqlSession openSession = this.getSqlSession();
		openSession.insert("test.insertUser", user);
		// 记得提交事务
		openSession.commit();
	}

	// 更改用户数据
	public void updateUserById(User user) {
		SqlSession openSession = this.getSqlSession();
		openSession.update("test.updateUserById", user);
		openSession.commit();
	}
	
	// 删除用户
	public void delUserById(Integer id) {
		SqlSession openSession = this.getSqlSession();
		openSession.delete("test.delUserById", id);
		openSession.commit();
	}
}

步骤三:测试文件

     UserDaoTest.java:

package com.jadan.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jadan.dao.UserDao;
import com.jadan.pojo.User;

public class UserDaoTest {
	private ApplicationContext applicationContext;
	
	// 在所有测试文件之前执行 
	@Before
	public void setUp() throws Exception {
		String configLocation = "ApplicationContext.xml";
		applicationContext = new ClassPathXmlApplicationContext(configLocation);
	}
	
	@Test
	public void testFindUserById() throws Exception {
		// 获取UserDao对象,getBean中的字符串是在ApplicationContext.xml中声明中
		UserDao userDao = (UserDao) applicationContext.getBean("userDao");
		
		User user = userDao.findUserById(1);
		System.out.println(user);
	}
}

下一篇:整合后Mapper接口代理实现

猜你喜欢

转载自blog.csdn.net/jonez/article/details/81083643