MyBatis基礎知識

MyBatis基礎知識
1 Star2 Stars3 Stars4 Stars5 Stars 給文章打分!
Loading...

dao:RoleMapper.java

package cn.bdqn.dao;
import java.util.List;
import cn.bdqn.pojo.Role;
public interface RoleMapper {
public void add(Role role);
public void update(Role role);
public void delete(Role role);
public List<Role> getRoleList();
}

dao:RoleMapper.xml

<pre name="code" class="java"><?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="cn.bdqn.dao.RoleMapper">
<!-- where/if(判斷引數) - 將實體類不為空的屬性作為where條件, 能智慧的處理 and or ,不必擔心多餘導致語法錯誤-->  
<!-- <select id="getRoleList" resultType="Role" parameterType="Role">
select * from role
<where>
<if test="roleCode != null">
and roleCode like CONCAT ('%',#{roleCode},'%')
</if>
<if test="roleName != null">
and roleName like CONCAT ('%',#{roleName},'%')
</if>
</where>
</select> -->
<!-- if/trim代替where(判斷引數) - 將實體類不為空的屬性作為where條件 -->
<!--  <select id="getRoleList" resultType="Role" parameterType="Role">
select * from role
<trim prefix="where" prefixOverrides="and | or">
<if test="roleCode != null">
and roleCode like CONCAT ('%',#{roleCode},'%')
</if>
<if test="roleName != null">
and roleName like CONCAT ('%',#{roleName},'%')
</if>
</trim>
</select> -->
<!-- choose(判斷引數) - 按順序將實體類第一個不為空的屬性作為where條件 -->
<select id="getRoleList" resultType="Role" parameterType="Role">
select * from role
<where>
<choose>
<when test="roleCode != null">
and roleCode like CONCAT ('%',#{roleCode},'%')
</when>
<when test="roleName != null">
and roleName like CONCAT ('%',#{roleName},'%')
</when>
<otherwise></otherwise>
</choose>
</where>
</select>
<insert id="add" parameterType="Role">
insert into role (roleCode,roleName) 
values (#{roleCode},#{roleName})
</insert>
<update id="update" parameterType="Role">
update role set roleCode=#{roleCode},roleName=#{roleName}
where id=#{id}
</update>
<delete id="delete" parameterType="Role">
delete from role where id=#{id}
</delete>
</mapper>

dao:UserMapper.java

<pre name="code" class="java">package cn.bdqn.dao;
import java.util.List;
import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.User;
public interface UserMapper {
public int count();
public void add(User user);
public void update(User user);
public void delete(User user);
public List<User> getUserList();
//根據roleId獲取使用者列表
public List<User> getUserListByRoleId(Role role);
//獲取指定使用者的地址列表(user表-address表:1對多關係)
public User getAddressListByUserId(User user);
//根據條件,獲取使用者表資料列表(動態sql)
public List<User> searchUserList(User user);
//根據部門條件,獲取使用者表資料列表-foreach_array
public List<User> getUserByDepId_foreach_array(String[] depIds);
//根據部門條件,獲取使用者表資料列表-foreach_list
public List<User> getUserByDepId_foreach_list(List<String> depIdList);
}

dao:UserMapper.xml

<pre name="code" class="java"><?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">
<!-- namespace的名字需要跟介面的類名一致 -->
<mapper namespace="cn.bdqn.dao.UserMapper">
<!-- 
1、resultMap屬性:type為java實體類;id為此resultMap的標識
2、resultMap的子元素:
id – 一般對應到資料庫中該行的ID,設定此項可以提高Mybatis效能.
result – 對映到JavaBean 的某個“簡單型別”屬性,String,int等.
association – 對映到JavaBean 的某個“複雜型別”屬性,其他JavaBean類.
collection –複雜型別集合 
-->
<!--根據roleId獲取使用者列表: 當資料庫中的欄位資訊與物件的屬性不一致時需要通過resultMap來對映 -->
<!-- <resultMap type="User" id="seachUserResult">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="roleId" column="roleId"/>
<result property="roleName" column="roleName"/>
</resultMap>
<select id="getUserListByRoleId" parameterType="Role" resultMap="seachUserResult">
select u.*,r.roleName as roleName from user u,role r where u.roleId = r.id and u.roleId = #{id}
</select> -->
<!-- 根據roleId獲取使用者列表 association start-->
<resultMap type="User" id="seachUserResult">
<result property="id" column="id"/>
<result property="userCode" column="userCode" />
<result property="userName" column="userName" />
<result property="roleId" column="roleId" />
<!-- <association property="role" javaType="Role" >
<result property="id" column="id"/>
<result property="roleCode" column="roleCode"/>
<result property="roleName" column="roleName"/>
</association> -->
<association property="role" javaType="Role" resultMap="roleMap"/>
</resultMap>
<resultMap type="Role" id="roleMap">
<result property="id" column="id"/> 
<result property="roleCode" column="roleCode"/> 
<result property="roleName" column="roleName"/> 
</resultMap>
<select id="getUserListByRoleId" parameterType="Role" resultMap="seachUserResult">
select u.*,r.roleCode as roleCode,r.roleName as roleName from user u,role r where u.roleId = r.id and u.roleId = #{id}
</select>
<!-- association end-->
<!-- 獲取指定使用者的地址列表(user表-address表:1對多關係) collection start-->
<resultMap type="User" id="userMap">
<id property="id" column="userId"/>
<collection property="addressList" ofType="Address">
<id property="id" column="a_id"/>
<result property="postCode" column="postCode"/>
<result property="addressContent" column="addressContent"/>
</collection>
</resultMap>
<select id="getAddressListByUserId" parameterType="User" resultMap="userMap">
select *,a.id as a_id from user u,address a where u.id=a.userId and u.id=#{id}
</select>
<!-- collection end -->
<resultMap type="User" id="seachUser">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
<result property="roleId" column="roleId"/>
<result property="roleName" column="roleName"/>
</resultMap>
<!-- <select id="searchUserList" parameterType="User" resultMap="seachUser">
select u.*,r.roleName as roleName from user u,role r where u.roleId = r.id
and u.roleId = #{roleId}
and u.userCode like CONCAT ('%',#{userCode},'%')  
and u.userName like CONCAT ('%',#{userName},'%') 
</select> -->
<!-- 
1、有些時候,sql語句where條件中,需要一些安全判斷,例如按性別檢索,如果傳入的引數是空的,此時查詢出的結果很可能是空的,也許我們需要引數為空時,是查出全部的資訊。這是我們可以使用動態sql,增加一個判斷,當引數不符合要求的時候,我們可以不去判斷此查詢條件。
2、mybatis 的動態sql語句是基於OGNL表示式的。可以方便的在 sql 語句中實現某些邏輯. 總體說來mybatis 動態SQL 語句主要有以下幾類: 
if 語句 (簡單的條件判斷) 
choose (when,otherwize) ,相當於java 語言中的 switch ,與 jstl 中的choose 很類似.
trim (對包含的內容加上 prefix,或者 suffix 等,字首,字尾) 
where (主要是用來簡化sql語句中where條件判斷的,能智慧的處理 and or ,不必擔心多餘導致語法錯誤) 
set (主要用於更新時) 
foreach (在實現 mybatis in 語句查詢時特別有用) 
-->
<!--  if(判斷引數) - 將實體類不為空的屬性作為where條件 -->
<select id="searchUserList" parameterType="User" resultMap="seachUser">
select u.*,r.roleName as roleName from user u,role r where u.roleId = r.id
<if test="roleId!=null">
and u.roleId = #{roleId}
</if>
<if test="userCode != null">
and u.userCode like CONCAT ('%',#{userCode},'%')  
</if>
<if test="userName != null">
and u.userName like CONCAT ('%',#{userName},'%') 
</if>
</select>
<select id="count" resultType="int">
select count(1) from user
</select>
<insert id="add" parameterType="User">
insert into user (userCode,userName,userPassword) 
values (#{userCode},#{userName},#{userPassword})
</insert>
<!-- if/set(判斷引數) - 將實體類不為空的屬性更新 -->  
<!-- <update id="update" parameterType="User">
update user 
<set>
<if test="userCode != null and userCode != ''">userCode=#{userCode},</if>
<if test="userName != null">userName=#{userName},</if>
<if test="userPassword != null">userPassword=#{userPassword},</if>
<if test="roleId != null">roleId=#{roleId}</if>
</set>
where id=#{id}
</update> -->
<!-- if/trim代替set(判斷引數) - 將實體類不為空的屬性更新 --> 
<update id="update" parameterType="User">
update user 
<trim prefix="set" suffixOverrides=",">
<if test="userCode != null and userCode != ''">userCode=#{userCode},</if>
<if test="userName != null">userName=#{userName},</if>
<if test="userPassword != null">userPassword=#{userPassword},</if>
<if test="roleId != null">roleId=#{roleId}</if>
</trim>
where id=#{id}
</update>
<!--注意: 你可以傳遞一個List例項或者陣列作為引數物件傳給MyBatis。
當你這麼做的時候,MyBatis會自動將它包裝在一個Map中,用名稱在作為鍵。
List例項將會以“list”作為鍵,而陣列例項將會以“array”作為鍵。
配置檔案中的parameterType是可以不配置的-->
<resultMap type="User" id="userMapByDep">
<result property="id" column="id"/>
<result property="userCode" column="userCode"/>
<result property="userName" column="userName"/>
</resultMap>
<!-- foreach(迴圈array引數) - 作為where中in的條件 -->
<select id="getUserByDepId_foreach_array" resultMap="userMapByDep">
select * from user  where depId in 
<foreach collection="array" item="depIds" open="(" separator="," close=")">
#{depIds}
</foreach>
</select>
<!-- foreach(迴圈List<String>引數) - 作為where中in的條件 -->
<select id="getUserByDepId_foreach_list" resultMap="userMapByDep">
select * from user  where depId in 
<foreach collection="list" item="depIdList" open="(" separator="," close=")">
#{depIdList}
</foreach>
</select>
<delete id="delete" parameterType="User">
delete from user where id=#{id}
</delete>
<select id="getUserList" resultType="User">
select * from user
</select>
</mapper>

pojo:Role.java

package cn.bdqn.pojo;
public class Role {
private Integer id;
private String roleCode;
private String roleName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}

pojo:User.java

package cn.bdqn.pojo;
import java.util.List;
public class User {
private Integer id;
private String userName;
private String userCode;
private String userPassword;
private Integer roleId;
private String roleName;
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}

pojo:Address.java

package cn.bdqn.pojo;
public class Address {
private Integer id;
private Integer postCode;
private String addressContent;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPostCode() {
return postCode;
}
public void setPostCode(Integer postCode) {
this.postCode = postCode;
}
public String getAddressContent() {
return addressContent;
}
public void setAddressContent(String addressContent) {
this.addressContent = addressContent;
}
}

test:RoleDaoTest.java

package cn.bdqn.test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import cn.bdqn.dao.RoleMapper;
import cn.bdqn.pojo.Role;
import cn.bdqn.util.MyBatisUtil;
public class RoleDaoTest {
private Logger logger = Logger.getLogger(RoleDaoTest.class);
@Test
public void addTest() {
SqlSession sqlSession = null;
Role role = new Role();
role.setRoleCode("SALE");
role.setRoleName("銷售");
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(RoleMapper.class).add(role);
//sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void updateTest(){
SqlSession sqlSession = null;
Role role = new Role();
role.setId(5);
role.setRoleCode("SALE-1");
role.setRoleName("銷售-1");
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(RoleMapper.class).update(role);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void deleteTest(){
SqlSession sqlSession = null;
Role role = new Role();
role.setId(5);
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(RoleMapper.class).delete(role);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void getRoleListTest(){
SqlSession sqlSession = null;
Role role = new Role();
role.setRoleCode("a");
role.setRoleName("財");
List<Role> roleList = new ArrayList<Role>();
try {
sqlSession = MyBatisUtil.createSqlSession();
roleList = sqlSession.getMapper(RoleMapper.class).getRoleList(role);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(Role _role : roleList){
logger.debug("role---> "   _role.getRoleName());
}
}
}

test:UserDaoTest.java

package cn.bdqn.test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import cn.bdqn.pojo.User;
import cn.bdqn.util.MyBatisUtil;
public class UserDaoTest {
private Logger logger = Logger.getLogger(UserDaoTest.class);
@Test
public void countTest() {
SqlSession sqlSession = null;
int count = 0;
try {
sqlSession = MyBatisUtil.createSqlSession();
count = sqlSession.selectOne("cn.bdqn.dao.UserMapper.count");
} catch (Exception e) {
// TODO: handle exception
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("countTest count---> "   count);
}
@Test
public void addTest(){
SqlSession sqlSession = null;
int count = 0;
User user = new User();
user.setUserCode("t03");
user.setUserName("北大青鳥");
user.setUserPassword("123456");
try {
sqlSession = MyBatisUtil.createSqlSession();
count = sqlSession.insert("cn.bdqn.dao.UserMapper.add", user);
//sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("addTest count---> "   count);
Assert.assertEquals(1, count);
}
@Test
public void updateTest(){
SqlSession sqlSession = null;
int count = 0;
User user = new User();
user.setId(11);
user.setUserCode("t03");
user.setUserName("北大青鳥");
user.setUserPassword("123456");
try {
sqlSession = MyBatisUtil.createSqlSession();
count = sqlSession.update("cn.bdqn.dao.UserMapper.update", user);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("updateTest count---> "   count);
Assert.assertEquals(1, count);
}
@Test
public void deleteTest(){
SqlSession sqlSession = null;
int count = 0;
User user = new User();
user.setId(11);
try {
sqlSession = MyBatisUtil.createSqlSession();
count = sqlSession.delete("cn.bdqn.dao.UserMapper.delete", user);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("deleteTest count---> "   count);
Assert.assertEquals(1, count);
}
@Test
public void getUserListTest(){
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.selectList("cn.bdqn.dao.UserMapper.getUserList");
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(User user: userList){
logger.debug("getUserListTest username:---> "   user.getUserName());
}
}
}

test:UserDaoTestByMapper.java

package cn.bdqn.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import cn.bdqn.dao.UserMapper;
import cn.bdqn.pojo.User;
import cn.bdqn.util.MyBatisUtil;
public class UserDaoTestByMapper{
private Logger logger = Logger.getLogger(UserDaoTestByMapper.class);
@Test
public void countTest() {
SqlSession sqlSession = null;
int count = 0;
try {
sqlSession = MyBatisUtil.createSqlSession();
//在getMapper方法裡傳入UserMapper這個class就會自動把userMapper裡的方法注入進來
count = sqlSession.getMapper(UserMapper.class).count();
} catch (Exception e) {
// TODO: handle exception
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("countTest count---> "   count);
}
@Test
public void addTest(){
SqlSession sqlSession = null;
User user = new User();
user.setUserCode("t04");
user.setUserName("fdfd");
user.setUserPassword("123456");
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(UserMapper.class).add(user);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void updateTest(){
SqlSession sqlSession = null;
User user = new User();
user.setId(7);
user.setUserCode("");
//		user.setUserName("88888");
user.setUserPassword("33333");
user.setRoleId(3);
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(UserMapper.class).update(user);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void deleteTest(){
SqlSession sqlSession = null;
User user = new User();
user.setId(11);
try {
sqlSession = MyBatisUtil.createSqlSession();
sqlSession.getMapper(UserMapper.class).delete(user);
sqlSession.commit();
} catch (Exception e) {
// TODO: handle exception
sqlSession.rollback();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
}
@Test
public void getUserListTest(){
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).getUserList();
} catch (Exception e) {
// TODO: handle exception
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("getUserListTest count---> "   userList.size());
}
/*@Test
public void getUserListByRoleIdTest(){
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
Role role = new Role();
role.setId(2);
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).getUserListByRoleId(role);
} catch (Exception e) {
// TODO: handle exception
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("getUserListByRoleIdTest count---> "   userList.size());
for(User user:userList){
logger.debug("===== "  user.getUserName()   ","   user.getRoleName());
}
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
Role role = new Role();
role.setId(2);
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).getUserListByRoleId(role);
} catch (Exception e) {
// TODO: handle exception
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("getUserListByRoleIdTest count---> "   userList.size());
for(User user:userList){
logger.debug("===== "  user.getUserName()   ","   user.getRole().getRoleName());
}
}
@Test
public void getAddressListByUserIdTest(){
SqlSession sqlSession = null;
User user = new User();
user.setId(1);
try{
sqlSession = MyBatisUtil.createSqlSession();
user = sqlSession.getMapper(UserMapper.class).getAddressListByUserId(user);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
logger.debug("getAddressListByUserIdTest===========> userId: "   user.getId());
logger.debug("--- "   user.getAddressList().size());
for(Address address : user.getAddressList()){
logger.debug("Address===========> "   address.getAddressContent());
}
}*/
@Test
public void searchUserListTest(){
//LogFactory.useLog4JLogging();//log日誌輸出
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
User user = new User();
//user.setRoleId(1);
//user.setUserCode("T");
user.setUserName("測試");
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).searchUserList(user);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(User _user : userList){
logger.debug("_user===========> "   _user.getUserName());
}
}
@Test
public void getUserByDepId_foreach_arrayTest(){
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
String[] depIds = {"1","2","4"};
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).getUserByDepId_foreach_array(depIds);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(User _user : userList){
logger.debug("_user===========> "   _user.getUserName());
}
}
@Test
public void getUserByDepId_foreach_listTest(){
SqlSession sqlSession = null;
List<User> userList = new ArrayList<User>();
List<String> depIdList = new ArrayList<String>();
depIdList.add("1");
depIdList.add("2");
depIdList.add("4");
try {
sqlSession = MyBatisUtil.createSqlSession();
userList = sqlSession.getMapper(UserMapper.class).getUserByDepId_foreach_list(depIdList);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyBatisUtil.closeSqlSession(sqlSession);
}
for(User _user : userList){
logger.debug("_user===========> "   _user.getUserName());
}
}
}

test:UserTest.java

package cn.bdqn.test;
import static org.junit.Assert.*;
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.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
import cn.bdqn.pojo.User;
public class UserTest {
private Logger logger = Logger.getLogger(UserTest.class);
@Test
public void countTest() {
String resource = "mybatis-config.xml";
int count = 0;
SqlSession sqlSession = null;
try {
//1 獲取mybatis-config.xml的輸入流
InputStream is = Resources.getResourceAsStream(resource);
//2 建立SqlSessionFactory物件,完成對配置檔案的讀取
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3 建立sqlSession
sqlSession = factory.openSession();
//4 呼叫mapper檔案來對資料進行操作,必須先把mapper檔案引入到mybatis-config.xml中
count = sqlSession.selectOne("cn.bdqn.dao.UserMapper.count");
logger.debug("count---> "   count);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
sqlSession.close();
}
}
@Test
public void addTest(){
String resource = "mybatis-config.xml";
SqlSession sqlSession = null;
int count = 0;
User user = new User();
user.setUserCode("t01");
user.setUserName("erhuo");
user.setUserPassword("123456");
try {
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
sqlSession = factory.openSession();
count = sqlSession.insert("cn.bdqn.dao.UserMapper.add",user);
logger.debug("add count---> "   count);
sqlSession.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
sqlSession.rollback();
e.printStackTrace();
}finally{
sqlSession.close();
}
Assert.assertEquals(1, count);
}
}

util:MyBatisUtil.java

package cn.bdqn.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private static SqlSessionFactory factory;
/**
* 一般情況下,如果有些程式碼必須在專案啟動的時候就執行的時候,需要使用靜態程式碼塊,這種程式碼是主動執行的;
* 需要在專案啟動的時候就初始化,在不建立物件的情況下,其他程式來呼叫的時候,需要使用靜態方法,這種程式碼是被動執行的.
* 靜態方法在類載入的時候 就已經載入 可以用類名直接呼叫
*/
static{//在靜態程式碼塊下,factory只會被建立一次
System.out.println("static factory===============");
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
factory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
}
public static SqlSession createSqlSession(){
return factory.openSession();//true 為自動提交事務
}
public static void closeSqlSession(SqlSession sqlSession){
if(null != sqlSession) 
sqlSession.close();
}
}

jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/testdb
username=root
password=xxxxxx
driver=com.mysql.jdbc.Driver

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 通過這個配置檔案完成mybatis與資料的連線 -->
<configuration>
<!-- 引入jdbc.properties檔案 -->
<properties resource="jdbc.properties"/>
<!-- 配置mybatis的log實現為LOG4J -->
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<!-- 型別別名 -->
<typeAliases>
<!-- 
<typeAlias type="cn.bdqn.pojo.User" alias="User"/>
-->
<package name="cn.bdqn.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<!-- 配置事務管理,採用JDBC的事物管理 -->
<transactionManager type="JDBC"/>
<!-- POOLED:mybatis自帶的資料來源 JNDI:基於tomcat的資料來源 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>	
</environment>
</environments>
<!-- 講mapper檔案加入到配置檔案中 -->
<mappers>
<mapper resource="cn/bdqn/dao/UserMapper.xml"/>
<mapper resource="cn/bdqn/dao/RoleMapper.xml"/>
</mappers>
</configuration>

相關文章

程式語言 最新文章