/u012881904/article/details/75452546 经过第一次的学习mybatis之后,我们对于这个有了简单的了解和认识之后呢,就可以简单的使用啦,昨天呢,我们仅仅是使用了简单的一个查询的功能,对于一些常用的findAll,findBy..,deleteByIds,deleteByid,add等等功能,基本的了解还是十分的有必要的。就在昨天的基础之上进行复制,重新处理了一个projetc进行说明。
mybaitsFactory的简单的封装
package mon.utils;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.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;/*** descrption: 获取Sqlsession* authohr: wangji* date: -07-20 8:34*/public class MybatisSessionFactory{private static final Logger log = LoggerFactory.getLogger(MybatisSessionFactory.class);private static volatile SqlSessionFactory sqlSessionFactory;public static SqlSessionFactory getInstatnce(){if(sqlSessionFactory == null){synchronized (MybatisSessionFactory.class){if(sqlSessionFactory ==null){try {sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));} catch (IOException e) {log.error("mybatits 启动异常");}}}}return sqlSessionFactory;};public static SqlSession getSQLSesssion(){if( getInstatnce() !=null){return sqlSessionFactory.openSession();}return null;}public static void closeSession(SqlSession sqlSession){if(sqlSession !=null){sqlSession.close();}}}
重点在于我们的Dao层也就是Dao接口,同时在Mybatis中我们也可以认为是Mapping层的操作,我们看看接口需要实现一些什么样的功能。
package com.jet.module.UserManage.dao;import com.jet.module.UserManage.entity.User;import java.util.List;import java.util.Map;/*** Created by JetWang on /7/19.*/public interface UserDao {User findById(Integer id);List<User> findAll();//这里只是插入一个数据void addUser(User user);//这里插入多个数据void addUsers(List<User> userList);void deleteById(Integer id);void deleteByIds(List<Integer> ids);void deleteByArrayIds(Integer []ids);void deleteByMapIds(Map<String,Object> map);}
下面一个个的进行讲解
findAll我们查找出来的时候是个List,必须使用ResultMap进行处理,ResultMap很强大,可以想象成为一个简单的Bean或者是一个List< Bean>的集合,我们SQL查找后的字段对于column,Bean中的属性也就是对应property.
<resultMap id="listUser" type="User"><!--type对应我们list中的实体,或者就是一个JavaBean--><id column="id" property="id" /><!--column不是我们数据库中的字段名称,而是查找出来之后对应的字段的信息--><result column="name" property="name" /><result column="age" property="age" /><result column="address" property="address" /></resultMap><!--resultMap 很强大,这里只是返回了一个List的数据而已--><select id="findAll" resultMap="listUser" >select id,userName as name,userAge as age,userAddress as address from user</select>
addUser 插入一个数据,由于一般来说自增的主键,我们这里也是需要配置使用,useGeneratedKeys使用key,然后对于的属性为id.除此之外我们传入的使用User的Bean我们可以想象为Map,其实这里想象为Map或者Bean都是差不多的的,对于#{}中的对象就是属性或者键值。
<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id" >INSERT INTO USER(userName,userAge,userAddress) VALUES(#{name},#{age},#{address} )</insert>
addUsers这中批量增加的需要动态的SQL支持,这里使用了重构SQL标签减少重复的使用相同的文字。foreach 很好理解吧,集合就是list或者array或者map中的键,item就是当前的一个项,index是第几项,分割符意思就是每一项分割使用的分隔符。
<!--这里的inser into后面的 user(userName,userAge,userAddress)重复的使用,mybatis中提供了重构的--><sql id="insertUserColumn">USER(userName,userAge,userAddress)</sql><!--所有的属性都必须在一行中书写完成哦--><insert id="addUsers" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="id">INSERT INTO <include refid="insertUserColumn"></include> VALUES<foreach collection="list" item="item" index="index" separator=",">/*这里的分割符是插入之后的分割符*/(#{item.name},#{item.age},#{item.address})</foreach>/*(wangji,1,'zunyi'),(wangji,1,'zunyi') 动态SQl的强大之处*/</insert>
delete一样的就不用多说了
<delete id="deleteById" parameterType="int" >DELETE FROM USER WHERE id = #{id}</delete><delete id="deleteByIds" parameterType="java.util.List" >DELETE FROM USER WHERE id in /*open 和close就是构建的时候需要括号包起来这个sql语句*/<foreach collection="list" separator="," index="index" open="(" close=")" item="item">#{item}/*这里的list中就是一个包装Integer,所以就是这个自己本身*/</foreach></delete><!--/u013083576/article/details/51577954 这种写法--><delete id="deleteByArrayIds" parameterType="int[]" >DELETE FROM USER WHERE id in<foreach collection="array" separator="," index="index" open="(" close=")" item="item">#{item}</foreach></delete><delete id="deleteByMapIds" parameterType="java.util.Map">DELETE FROM USER WHERE id in/*这里的ids是放置在Map中的键,值可能是数组或者List*/<foreach collection="ids" separator="," index="index" open="(" close=")" item="item">#{item}</foreach></delete>
测试一下(包含了昨天的内容)
import mon.utils.MybatisSessionFactory;import com.jet.module.UserManage.dao.UserDao;import com.jet.module.UserManage.entity.User;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Assert;import org.junit.Test;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/*** Created by JetWang on /7/19.*/public class UserDaoTest {//添加了日志private static final Logger log = LoggerFactory.getLogger(UserDaoTest.class);@Testpublic void testDeleteByMapIds(){SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);Integer[] ids = {8,9};Map<String,Object> map = new HashMap<String,Object>();map.put("ids",ids);userDao.deleteByMapIds(map);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}}@Testpublic void testDeleteByIdsArray(){SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);Integer[] ids = {8,9};userDao.deleteByArrayIds(ids);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}}@Testpublic void testDeleteByIdsList(){SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);List<Integer> ids = new ArrayList<Integer>();ids.add(10);ids.add(11);userDao.deleteByIds(ids);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}}@Testpublic void testDeleteById(){SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);userDao.deleteById(6);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}}@Testpublic void testAddUsers(){List<User> userList = new ArrayList<User>(5);for(int i=0;i<5;i++){User user = new User();user.setAge(i);user.setAddress("zunyi"+i);user.setName("wangji"+i);userList.add(user);}SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);userDao.addUsers(userList);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}log.info(userList.toString());}@Testpublic void testAddUser(){User user = new User();user.setName("wangwang");user.setAddress("zunyi");user.setAge(5);SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);userDao.addUser(user);//这里需要提交事务才能写入数据库mit();} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}log.info(user.toString());}@Testpublic void testFindAll(){SqlSession sqlSession = MybatisSessionFactory.getSQLSesssion();try {UserDao userDao = sqlSession.getMapper(UserDao.class);log.info(userDao.findAll().toString());} catch (Exception e) {log.error(e.getMessage(),e);} finally {MybatisSessionFactory.closeSession(sqlSession);}}@Testpublic void testSessionFactory(){Assert.assertNotNull(MybatisSessionFactory.getInstatnce());}@Testpublic void findByIdTest() {InputStream inputStream = null;SqlSessionFactory sqlSessionFactory = null;SqlSession sqlSession = null;try {inputStream = org.apache.ibatis.io.Resources.getResourceAsStream("mybatis-config.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);sqlSession = sqlSessionFactory.openSession();//这里面向接口的,mybatis使用动态代理给你生成实现类,不需要DaoImplUserDao userDao = sqlSession.getMapper(UserDao.class);User user = userDao.findById(1);/*通过命名空间进行查询User user = sqlSession.selectOne("com.jet.module.UserManage.dao.UserDao.findById",1);*/Assert.assertNotNull(user);System.out.println(user.toString());} catch (IOException e) {e.printStackTrace();} finally {if (inputStream != null) {try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (sqlSession != null) {sqlSession.close();}}}}
资源地址:/WangJi92/mybatits-study/blob/master/mybatis-study/study-2