1. 程式人生 > >mybatis學習筆記(二)之XML方式的基本用法

mybatis學習筆記(二)之XML方式的基本用法

在前一篇筆記中,我們建立了配置 mybatis-config.xml 檔案原來 mappers標籤下的內容為:

<mappers>  
    <mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml" /> 
</mappers> 

為了配置簡單,我們採用配置包的形式新增mapper介面,修改為:

<mappers>  
    <package name="tk.mybatis.simple.mapper" /> 
</mappers>

該種方式會去掃描tk.mybatis.simple.mapper包下的所有介面


接下來開始我們的專案,專案的目錄結構如下:

 


src/main/resources包的目錄結構



接下來是程式碼部分內容,程式碼主要就是SysUser.java實體、UserMapper.Java介面、UserMapper.xml對映檔案和UserMapperTest.Java測試程式碼四部分

SysUser.Java實體的程式碼

package tk.mybatis.simple.model;

public class SysUser {
	private Long id;
	private String userName;
	private String userPassword;
	private String userInfo;
	private byte[] headImg;
	private Date createTime;
	
	getter()、setter()方法
}

UserMapper.Java介面的程式碼:

package tk.mybatis.simple.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;

public interface UserMapper {

	/**
	 * 根據id查詢使用者
	 * @param id
	 * @return
	 */
	SysUser selectById(Long id);
	
	/**
	 * 查詢所有使用者
	 * @return
	 */
	List<SysUser> selectAll();
	
	/**
	 * 新增使用者
	 * @param sysUser
	 * @return
	 */
	int insert(SysUser sysUser);
	
	/**
	 * 更新使用者
	 * @param sysUser
	 * @return
	 */
	int update(SysUser sysUser);
	
	/**
	 * 根據id刪除使用者
	 * @param sysUser
	 * @return
	 */
	int delete(SysUser sysUser);
	
	/**
	 * 獲取使用者角色
	 * @param userId
	 * @param enabled
	 * @return
	 */
	List<SysRole> selectRolesByUserIdAndRoleEnabled(
			@Param("userId")Long userId, @Param("enabled")Integer enabled);
}

UserMapper.xml對映檔案的程式碼:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="tk.mybatis.simple.mapper.UserMapper">

	<resultMap type="tk.mybatis.simple.model.SysUser" id="sysUserMap">
		<id property="id" column="id" />
		<result property="userName" column="user_name" />
		<result property="userPassword" column="user_password" />
		<result property="userInfo" column="user_info" />
		<result property="headImg" column="head_img" />
		<result property="createTime" column="create_time" jdbcType="TIMESTAMP" />
	</resultMap>
	
	<select id="selectById" resultMap="sysUserMap">
		select * from sys_user where id = #{id}
	</select>
		
	<select id="selectAll" resultMap="sysUserMap">
		select * from sys_user
	</select>
	
	<insert id="insert" useGeneratedKeys="true" keyProperty="id">
		insert into sys_user(user_name, user_password, user_info, head_img, create_time) 
		values(#{userName}, #{userPassword}, #{userInfo}, #{headImg, jdbcType=BLOB}, #{createTime, jdbcType=TIMESTAMP})
	</insert>
	
	<insert id="insert2">
		insert into sys_user(user_name, user_password, user_info, head_img, create_time) 
		values(#{userName}, #{userPassword}, #{userInfo}, #{headImg, jdbcType=BLOB}, #{createTime, jdbcType=TIMESTAMP})
		<selectKey keyColumn="id" keyProperty="id" resultType="long" order="AFTER">
			select last_insert_id()			
		</selectKey>
	</insert>
	
	<insert id="insert3">
		<selectKey keyColumn="id" keyProperty="id" resultType="long" order="BEFORE"> 
			select seq_id.nextval from dual
		</selectKey>
		insert into sys_user(id, user_name, user_password, user_info, head_img, create_time) 
		values(#{id}, #{userName}, #{userPassword}, #{userInfo}, #{headImg, jdbcType=BLOB}, #{createTime, jdbcType=TIMESTAMP})
	</insert>
	
	<update id="updateById">
		update sys_user
		set user_name = #{userName},
			user_password = #{userPassword},
			user_info = #{userInfo},
			head_img = #{headImg},
			create_time = #{createTime}
		where id = #{id}
	</update>
	
	<delete id="deleteById">
		delete from sys_user where id = #{id}
	</delete>
	
	<select id="selectRolesByUserIdAndRoleEnabled" resultType="SysRole">
		select r.id, r.role_name, r.enabled, r.create_by, r.create_time
		from sys_user u
		inner join sys_user_role ur on u.id = ur.user_id
		inner join sys_role r on ur.role_id = r.id
		where u.id = #{userId} and r.enabled = #{enabled}
	</select>
	
</mapper>

UserMapperTest.Java測試程式碼

package tk.mybatis.simple.mapper;

import java.util.Date;
import java.util.List;

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

import tk.mybatis.simple.model.SysUser;

public class UserMapperTest extends BaseMapperTest{
	
	@Test
	public void testSelectById(){
		SqlSession sqlSession = this.getSqlSession();
		try{
			//SysUser sysUser = sqlSession.selectOne("tk.mybatis.simple.mapper.UserMapper.selectById", "1");
			//獲取UserMapper介面
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			SysUser sysUser = userMapper.selectById(1L);
			Assert.assertNotNull(sysUser);
			System.out.printf("%-4d%4s %4s\n", sysUser.getId(), sysUser.getUserName(), sysUser.getUserPassword());
		}finally{
			sqlSession.close();
		}
	}
	
	@Test
	public void testSelectAll(){
		SqlSession sqlSession = this.getSqlSession();
		
		try{
			//List<SysUser> userList = sqlSession.selectList("tk.mybatis.simple.mapper.UserMapper.selectAll");
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			List<SysUser> userList = userMapper.selectAll();
			Assert.assertNotNull(userList);
			Assert.assertTrue(userList.size()>0);
			printUserList(userList);
		}finally{
			sqlSession.close();
		}
	}
	
	@Test
	public void testInsert(){
		SqlSession sqlSession = this.getSqlSession();
		try{
			UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
			SysUser user = new SysUser();
			//user.setUserName("test1");
			user.setUserPassword("123456");
			user.setHeadImg(new byte[]{1,2,3});
			user.setCreateTime(new Date());

			int result = userMapper.insert(user);
			Assert.assertEquals(1, result);
			//Assert.assertNull(user.getId());
		}finally{
			//預設的sqlSessionFactory.openSession()是不自動提交的
			sqlSession.rollback();
			sqlSession.close();
		}
		
	}
	
	
	private void printUserList(List<SysUser> userList) {
		for(SysUser sysUser : userList)
			System.out.printf("%-4d%4s %4s\n", sysUser.getId(), sysUser.getUserName(), sysUser.getUserPassword());
	}
}


以上內容純屬個人學習筆記,如果想詳細學習mybatis,可前往http://mybatis.tk/下載相關工具及專案程式碼