夜光序言:
丝丝青鸢,柒柒白菁。
鸢留青丝,箐染白柒。
零落柒丝,零怨箐鸢。
素璟白依,情落墨翊。
这是我夜光当初在培训mybatis时的心得体会,进行整理汇编,算是人生的历程~~
2.基本的CRUD操作
2.1 准备工作(继续使用前面的库表和代码)
2.2 别名与自定义别名
2.2.1 内置别名
对常用的 java 类型,已经内置了一些别名支持。这些别名都是不区分大小写的。(详细参看用户手机)
2.2.2 自定义别名
在myBatis的主配置文件给cn.itcast.entity.Dept类创建别名Dept,后继的DeptMapper.xml配置文件中可以使用别名
<!-- 通过别名简化对类的使用 -->
<typeAliases>
<typeAlias type="cn.Genius.entity.Dept" alias="Dept" />
</typeAliases>
2.3 MyBatisUtil工具类
public class MyBatisUtil {
private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sessionFactory;
private static String CONFIG_FILE_LOCATION = "myBatis-config.xml";
static {
try {
buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private MyBatisUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws Exception
*/
public static SqlSession getSession() throws Exception {
SqlSession session = (SqlSession) threadLocal.get();
if (session == null) {
if (sessionFactory == null) {
buildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* build session factory
*
*/
public static void buildSessionFactory() {
Reader reader=null;
try {
reader=Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Close the single session instance.
*
*/
public static void closeSession(){
SqlSession session = (SqlSession) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static SqlSessionFactory getSessionFactory() {
return sessionFactory;
}
}
2.3 CRUD操作
2.3.1 新增操作
配置文件DeptMapper.xml使用别名, DeptDaoImpl.java新增方法使用工具类。
修改配置文件DeptMapper.xml(使用别名):
<!--夜光:parameterType="Dept"不写时,也能自动根据代码传递的参数Dept自动匹配 内容-->
<insert id="insert" parameterType="Dept">
insert into dept(dept_name) values(#{deptName});
</insert>
修改DeptDaoImpl.java新增方法(使用MyBatisUtil.java工具类):
/**
* @param dept 部门信息
* @return 保存信息后受影响的行数
*/
public int saveDept(Dept dept) {
int i = 0;
try {
session = MyBatisUtil.getSession();
i = session.insert("cn.Genius.entity.DeptMapper.insertDept", dept);
session.commit();
} catch (Exception e) {
e.printStackTrace();
session.rollback();
} finally {
try {
MyBatisUtil.closeSession();
} catch (Exception e) {
e.printStackTrace();
}
}
return i;
}
2.3.2 修改操作
修改配置文件deptMapper.xml,添加
<update id="update" parameterType="Dept">
update dept set dept_name=#{deptName} ,dept_address=#{deptAddress} where dept_id=#{deptId}
</update>
修改DeptDaoImpl.java,添加update方法:
public int update(Dept dept){
SqlSession session = null;
int i=0;
try {
session=MyBatisUtil.getSession();
//夜光:方法的第一个参数为DeptMapper.xml文件的命名空间+id
i=session.update("cn.itcast.entity.DeptMapper.update",dept);
System.out.println("受影响行数:"+i);
session.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
session.rollback();
}finally{
MyBatisUtil.closeSession();
}
return i;
}
2.3.3 删除操作
修改配置文件deptMapper.xml,添加
<delete id="delete" parameterType="Dept">
delete from dept where dept_id=#{deptId}
</delete>
修改DeptDaoImpl.java,添加delete方法:
public int delete(Dept dept){
int i = 0;
try {
session=MyBatisUtil.getSession();
//方法的第一个参数为DeptMapper.xml文件的命名空间+id
i=session.delete("cn.Genius.entity.DeptMapper.delete",dept);
//System.out.println("受影响行数:"+i);
session.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
session.rollback();
}finally{
MyBatisUtil.closeSession();
}
return i;
}
2.3.4 查询操作(返回单条记录)
配置deptMapper.xml文件的resultMap元素及SQL查询语句
<!-- 表字段和实体属性命名一致时可以不配置 -->
<resultMap id="deptResultMap" type="Dept">
<id property="deptId" column="dept_id"/>
<result property="deptName" column="dept_name"/>
<result property="deptAddress" column="dept_address"/>
</resultMap>
<!—夜光:省略其它的配置信息 -->
<!—夜光:返回单条记录,表字段和对应实体属性命名一致时可以不使用resultMap属性配置,直接使用resultType="返回的全类名或别名",建议使用前者;查询结果为所有字段时,也可以用*表示 -->
<select id="selectOne" parameterType="int" resultMap="deptResultMap" >
select dept_id, dept_name from dept where dept_id=#{deptId}
</select>
修改DeptDaoImpl.java,添加selectOne方法:
public Dept selectOne(int deptId){
Dept dept=null;
try {
session=MyBatisUtil.getSession();
dept=(Dept)session.selectOne("cn.Genius.entity.DeptMapper.selectOne",deptId);
System.out.println("dept:"+dept);
} catch (Exception e) {
e.printStackTrace();
}finally{
MyBatisUtil.closeSession();
}
return dept;
}
2.3.5 查询操作(返回多条记录)
修改配置文件deptMapper.xml,添加
<!-- 返回多条记录,返回结果配置的不是集合类型,而是集合元素的类型;参数也可以通过Map等方式封装 -->
<select id="selectList" parameterType="Map" resultMap="deptResultMap">
select * from dept where dept_name like #{deptName}
</select>
修改DeptDaoImpl.java,添加selectList方法:
public List<Dept> selectList(Map map){
List<Dept> depts=null;
try {
session=MyBatisUtil.getSession();
depts=session.selectList("cn.Genius.entity.DeptMapper.selectList",map);
} catch (Exception e) {
e.printStackTrace();
}finally{
MyBatisUtil.closeSession();
}
return depts;
}
测试类代码:
@Test
public void testSelectList() {
Map map=new HashMap();
map.put("deptName", "%研%");
List<Dept> depts=deptDaoImpl.selectList(map);
for(Dept dept:depts){
System.out.println("dept:"+dept);
}
}
3.动态SQL操作
3.1 准备工作
创建表及库,实体类,配置文件(参考上章节内容),以下为建表和库的SQL:
drop database if exists mybatis;
create database mybatis CHARACTER SET UTF8;
use mybatis;
create table dept(
dept_id int primary key auto_increment,
dept_name varchar(50),
dept_address varchar(50)
);
insert into dept(dept_name,dept_address) values('研发部一部','广州');
insert into dept(dept_name,dept_address) values('研发部二部','广州');
insert into dept(dept_name,dept_address) values('研发部三部','深圳');
select * from dept;
3.2 IF语句
修改配置文件deptMapper.xml,添加
<!-- 动态IF条件 -->
<select id="selectListUseIf" parameterType="Dept" resultMap="deptResultMap">
select * from dept where 1=1
<if test="deptId!=null">
and dept_id=#{deptId}
</if>
<if test="deptName!=null">
and dept_name=#{deptName}
</if>
<if test="deptAddress!=null">
and dept_address=#{deptAddress}
</if>
</select>
修改DeptDaoImpl.java,添加selectListUseIf方法:
//根据参数使用配置文件的IF语句自动填充查询的过滤条件
public List<Dept> selectListUseIf(Dept dept){
List<Dept> depts=null;
try {
session=MyBatisUtil.getSession();
depts=session.selectList("cn.Genius.entity.DeptMapper.selectListUseIf",dept);
} catch (Exception e) {
e.printStackTrace();
}finally{
MyBatisUtil.closeSession();
}
return depts;
}
3.3 WHERE语句
修改配置文件deptMapper.xml,添加
<!-- 动态Where条件 ,一般也需要与if结合使用,与纯if比较,省略了where 1=1-->
<select id="selectListUseWhere" parameterType="Dept" resultMap="deptResultMap">
select * from dept
<where>
<if test="deptId!=null">
and dept_id=#{deptId}
</if>
<if test="deptName!=null">
and dept_name=#{deptName}
</if>
<if test="deptAddress!=null">
and dept_address=#{deptAddress}
</if>
</where>
</select>
3.4 choose(when,otherwise)语句
修改配置文件deptMapper.xml,添加
<select id="selectListUseChoose" parameterType="Dept" resultMap="deptResultMap">
select * from dept where 1=1
<choose>
<when test="deptId!=null">and dept_id=#{deptId}</when>
<when test="deptName!=null">and dept_name=#{deptName}</when>
<when test="deptAddress!=null">and dept_address=#{deptAddress}</when>
<otherwise>and !1 = 1</otherwise>
</choose>
</select>
3.5 SET语句
修改配置文件deptMapper.xml,添加
<!--动态set语句可以用来更新数据 -->
<update id="updateUseSet" parameterType="Dept">
update dept
<set>
<if test="deptName!=null">dept_name=#{deptName},</if>
<if test="deptAddress!=null">dept_address=#{deptAddress},</if>
</set>
where dept_id=#{deptId}
</update>
3.6 ForEach语句
修改配置文件deptMapper.xml,添加
<!--夜光: 定义根据多个部门ID查询部门相关部门信息的SQL语句 ,resultMap的值是指集合里元素的类型,parameterType不用指定 -->
<select id="selectListUseForeach" resultMap="deptResultMap">
select * from dept where dept_id in
<!--夜光: collection="array或list",array用来对应参数为数组,list对应参数为 集合 -->
<foreach collection="array" item="deptId" open="(" separator="," close=")">
#{deptId}
</foreach>
</select>
3.7 include语句
修改配置文件deptMapper.xml,添加
<!-- 使用include语句动态插入表的字段及对应的值 -->
<sql id="key">
<!--suffixOverrides="," 可以忽略最后“,”号 -->
<trim suffixOverrides=",">
<if test="deptName!=null">
dept_name,
</if>
<if test="deptAddress!=null">
dept_address,
</if>
</trim>
</sql>
<sql id="value">
<trim suffixOverrides="," >
<if test="deptName!=null">
#{deptName},
</if>
<if test="deptAddress!=null">
#{deptAddress},
</if>
</trim>
</sql>
<insert id="insertUseInclude" parameterType="Dept">
insert into dept(
<include refid="key" />
) values(
<include refid="value"/>
)
</insert>
夜光练习
1、完成环境的配置及部门信息的添加
2、解决sqlsession线程安全问题(工具类封装)
3、完成单个部门查询和多个部门查询
4、根据指定部门编号(列表)修改部门信息地址为“武汉”