Java框架学习_Mybatis(六)Mybatis的动态代理模式

之前我们为了实现数据库操作的封装和业务的分离,使用Dao模式,现在Mybatis提供了更加简洁的动态代理模式,只要有接口不需要实现,就能进行数据库操作


动态代理模式必须遵循的规范:

  1. 与表相对应的mapper配置的namespace必须是接口的全路径名
  2. 接口的方法名必须与sql语句的id一致
  3. sql的parametertype必须与接口的形参一致
  4. sql的resultype必须与接口的返回值一致

这里再新建一个UserMapper.xml文件(要修改的地方就是namesapce,需要是接口的全路径名):





<mapper namespace="cn.nupt.mybatis.mapper.UserMapper">



<update id="updateUser" parameterType="cn.nupt.pojo.User" >


	UPDATE 
	  `mybatis`.`user` 
	SET
	 
	  `username` = #{username},	 
	  `address` = #{address} 
	  
	WHERE `id` = #{id} ;

update>




<delete id="deleteUser"  parameterType="int">

	delete from user where id  = #{id}


delete>

<select id="getUserById" parameterType="int" resultType="cn.nupt.pojo.User">

	
	 select * from user where id = ${value}

select>


<select id="getUserByName" parameterType="string" resultType="cn.nupt.pojo.User">

	
	
	
	select * from user where username like '%${value}%'

select>
mapper>

然后将这个mapper映射文件放到核心配置文件里:

<mappers>
		<mapper resource="mybatis/user.xml"/>
		
		<mapper resource="mybatis/UserMapper.xml"/>
mappers>

这里写一个增删查改的接口:

package cn.nupt.mybatis.mapper;

import java.util.List;

import cn.nupt.pojo.User;

public interface UserMapper {
	void updateUser(User user);

	void deleteUser(Integer id);

	User getUserById(Integer id);

	List<User> getUserByName(String name);

}

然后直接用动态代理就可以实现了:

package cn.nupt.mybatis.mapper;

import static org.junit.Assert.*;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import cn.nupt.mybatis.utils.SqlSessionFactoryUtils;
import cn.nupt.pojo.User;

public class UserMapperTest {

	@Test
	public void testUpdateUser() {

		SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true);
		// 获取接口的代理人实现类
		UserMapper userMapper = session.getMapper(UserMapper.class);

		User user = new User();

		user.setUsername("周杰伦");
		user.setAddress("台湾");
		user.setId(1);

		userMapper.updateUser(user);

	}

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

	@Test
	public void testGetUserById() {

		SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true);
		// 获取接口的代理人实现类
		UserMapper userMapper = session.getMapper(UserMapper.class);

		User userById = userMapper.getUserById(24);
		System.out.println(userById);
	}

	@Test
	public void testGetUserByName() {

		SqlSession session = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true);
		// 获取接口的代理人实现类
		UserMapper userMapper = session.getMapper(UserMapper.class);

		List<User> list = userMapper.getUserByName("%张%");
		for (User user : list) {
			System.out.println(user);
		}
	}

}

你可能感兴趣的:(SSM框架_Mybatis,JAVA框架SSM)