您的位置:首页 > 其它

mybatis知识点总结

2017-03-21 14:37 441 查看
1 mybatis 传表名和order by时必须用${},而不能用#

2 mybatis 返回类型是一个复合对象的话,用

<resultMap id="BaseResultMap" type="com.wanda.gmp.admin.dao.model.brand.Brand" >

 <id column="id" property="id" jdbcType="BIGINT" />

  <result column="zh_name" property="zhName" jdbcType="VARCHAR" />

<association property= "复合对象model中的名称" javaType="model中的对象名">

<result column="id" property="id"/>

<result column="name" property="name"/>

</association>

</resultMap>
3 mybatis resultType返回基本类型和对象,resultMap可以返回list

4 mybatis动态sql

(1)choose when otherWise 类似于if,where标签可以选用and

<where>

<choose>

<when test= "stu.id!=null">

  and id = #{stu.id}

</when>

<when></when>

<otherwise>

and gender= #{stu.gender}

</otherwise>

</choose>

<where>

(2)set标签可以选用逗号

update Student

<set>

<if test= "name != null">

name =#{name},

</if>

<if test= "brt != null">

birthday = #{brt},

</if>

</set>

(3)foreach标签

1、void insertCollection(List<RequirementPicture> list);

<insert id="insertCollection" parameterType="java.util.List">

    insert into requirement_picture (id, reference_type, reference_id,

    belongs_type, pic_id, seq_id,created_by, updated_by)

    values

    <foreach item="item" index="index" collection="list"

             separator=",">

      <trim prefix="(" suffixOverrides=", " suffix=")">

        #{item.id,jdbcType=BIGINT}, #{item.referenceType,jdbcType=TINYINT}, #

{item.referenceId,jdbcType=BIGINT},

        #{item.belongsType,jdbcType=TINYINT}, #{item.picId,jdbcType=VARCHAR}, #

{item.seqId,jdbcType=TINYINT},

        #{item.createdBy,jdbcType=VARCHAR}, #{item.updatedBy,jdbcType=VARCHAR}

      </trim>

    </foreach>

  </insert>

2、List<Brand> findByIds(List<Long> ids);

<select id="findByIds" resultMap="BaseResultMap" parameterType="java.util.List" >

    select

    <include refid="Base_Column_List" />

    from brand

    where id in

    <foreach collection="list" item="id" index="index" open="("

             close=")" separator=",">

      #{id}

    </foreach>

    and is_active=1

  </select>

(4)mybatis字符串拼接

1、<if test="name != null and name!=''" >

      and (d.full_name LIKE CONCAT('%',#{name,jdbcType=VARCHAR},'%')

    

      or e.zh_name LIKE CONCAT('%',#{name,jdbcType=VARCHAR},'%')

    

      or e.en_name LIKE CONCAT('%',#{name,jdbcType=VARCHAR},'%'))

    </if>

2、where name like '%${name}%'

3、通过bind标签避免$的危害

<select id= "queryStudent" parameterType="Student" resultMap = "studentResult">

<bind name= "pattern" value="'%'+ _parameter.getName()+'%'">

select id from Student where name like #{pattern}

</select>

5 databaseId用来连接不同类型的数据库

6  Mybatis中的TypeHandler是什么?

无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值

时,都会用类型处理器将获取的值以合适的方式转换成 Java 类型。Mybatis默认为我们实现了许多

TypeHandler, 当我们没有配置指定TypeHandler时,Mybatis会根据参数或者返回结果的不同,默认为我们

选择合适的TypeHandler处理。

mybatis中用typehandles可以进行model对象(javaType)和数据库类型(jdbcType)的转换,

我们在自定义TypeHandler的时候,可以在TypeHandler通过@MappedJdbcTypes指定jdbcType, 通过

@MappedTypes 指定javaType, 如果没有使用注解指定,那么我们就需要在配置文件中配置。

7 typeAliases节点主要用来设置别名,其实这是挺好用的一个功能, 通过配置别名,我们不用再指定完整的

包名,并且还能取别名。

例如: 我们在使用 com.demo.entity. UserEntity 的时候,我们可以直接配置一个别名user, 这样以后在

配置文件中要使用到com.demo.entity. UserEntity的时候,直接使用User即可。

也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user)

8

好啦,咱们就先来看看 insert, update, delete 怎么配置, 能配置哪些元素吧:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<!-- mapper 为根元素节点, 一个namespace对应一个dao -->
<mapper namespace="com.dy.dao.UserDao">

<insert
<!-- 1. id (必须配置)
id是命名空间中的唯一标识符,可被用来代表这条语句。
一个命名空间(namespace) 对应一个dao接口,
这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致 -->

id="insertUser"

<!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理)
将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理
parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) -->

parameterType="com.demo.User"

<!-- 3. flushCache (可选配置,默认配置为true)
将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:true(对应插入、更新和删除语句) -->

flushCache="true"

<!-- 4. statementType (可选配置,默认配置为PREPARED)
STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED。 -->

statementType="PREPARED"

<!-- 5. keyProperty (可选配置, 默认为unset)
(仅对 insert 和 update 有用)唯一标记一个属性,MyBatis 会通过 getGeneratedKeys 的返回值或者通过 insert 语句的 selectKey 子元素设置它的键值,默认:unset。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 -->

keyProperty=""

<!-- 6. keyColumn     (可选配置)
(仅对 insert 和 update 有用)通过生成的键值设置表中的列名,这个设置仅在某些数据库(像 PostgreSQL)是必须的,当主键列不是表中的第一列的时候需要设置。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 -->

keyColumn=""

<!-- 7. useGeneratedKeys (可选配置, 默认为false)
(仅对 insert 和 update 有用)这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段),默认值:false。  -->

useGeneratedKeys="false"

<!-- 8. timeout  (可选配置, 默认为unset, 依赖驱动)
这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)。 -->
timeout="20">

<update
id="updateUser"
parameterType="com.demo.User"
flushCache="true"
statementType="PREPARED"
timeout="20">

<delete
id="deleteUser"
parameterType="com.demo.User"
flushCache="true"
statementType="PREPARED"
timeout="20">
</mapper>


9

仔细观察上面parameterType,  "com.dy.entity.User",包名要是再长点呢,每次都这样写,写得蛋疼了。别忘了之前讲的 typeAliases(别名), 那么这个地方,用上别名,岂不是技能跟蛋疼的长长的包名说拜拜了。好啦,咱们配上别名,在哪儿配? 当然是在mybatis 的全局配置文件(我这儿名字是mybatis-conf.xml), 不要认为是在mapper的配置文件里面配置哈。
mybatis-conf.xml:

<typeAliases>
<!--
通过package, 可以直接指定package的名字, mybatis会自动扫描你指定包下面的javabean,
并且默认设置一个别名,默认的名字为: javabean 的首字母小写的非限定类名来作为它的别名。
也可在javabean 加上注解@Alias 来自定义别名, 例如: @Alias(user)
<package name="com.dy.entity"/>
-->
<typeAlias alias="user" type="com.dy.entity.User"/>
</typeAliases>


10 如果我们在使用mysql的时候,想在数据插入后返回插入的id, 我们也可以使用 selectKey 这个元素:

<!-- 对应userDao中的insertUser方法,  -->
<insert id="insertUser" parameterType="com.dy.entity.User">
<!-- oracle等不支持id自增长的,可根据其id生成策略,先获取id

<selectKey resultType="int" order="BEFORE" keyProperty="id">
select seq_user_id.nextval as id from dual
</selectKey>

-->

<!-- mysql插入数据后,获取id -->
<selectKey keyProperty="id" resultType="int" order="AFTER" >
SELECT LAST_INSERT_ID() as id
</selectKey>

insert into user(id, name, password, age, deleteFlag)
values(#{id}, #{name}, #{password}, #{age}, #{deleteFlag})
</insert>


 

这儿,我们就简单提一下 <selectKey> 这个元素节点吧:

<selectKey
<!-- selectKey 语句结果应该被设置的目标属性。如果希望得到多个生成的列,也可以是逗号分隔的属性名称列表。 -->
keyProperty="id"
<!-- 结果的类型。MyBatis 通常可以推算出来,但是为了更加确定写上也不会有什么问题。MyBatis 允许任何简单类型用作主键的类型,包括字符串。如果希望作用于多个生成的列,则可以使用一个包含期望属性的 Object 或一个 Map。 -->
resultType="int"
<!-- 这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素 - 这和像 Oracle 的数据库相似,在插入语句内部可能有嵌入索引调用。 -->
order="BEFORE"
<!-- 与前面相同,MyBatis 支持 STATEMENT,PREPARED 和 CALLABLE 语句的映射类型,分别代表 PreparedStatement 和 CallableStatement 类型。 -->
statementType="PREPARED">


当然,mysql在插入完成后(自增长id  useGeneratedKeys="true" keyProperty="id" ) ,在java后台可以通过直接调用刚插入实体的getId方式获得自增长id;

11

先看select的配置吧:

<select
<!--  1. id (必须配置)
id是命名空间中的唯一标识符,可被用来代表这条语句。
一个命名空间(namespace) 对应一个dao接口,
这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致  -->

id="selectPerson"

<!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理)
将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理
parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) -->
parameterType="int"

<!-- 3. resultType (resultType 与 resultMap 二选一配置)
resultType用以指定返回类型,指定的类型可以是基本类型,可以是java容器,也可以是javabean -->
resultType="hashmap"

<!-- 4. resultMap (resultType 与 resultMap 二选一配置)
resultMap用于引用我们通过 resultMap标签定义的映射类型,这也是mybatis组件高级复杂映射的关键 -->
resultMap="personResultMap"

<!-- 5. flushCache (可选配置)
将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false -->
flushCache="false"

<!-- 6. useCache (可选配置)
将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true -->
useCache="true"

<!-- 7. timeout (可选配置)
这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)-->
timeout="10000"

<!-- 8. fetchSize (可选配置)
这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)-->
fetchSize="256"

<!-- 9. statementType (可选配置)
STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED-->
statementType="PREPARED"

<!-- 10. resultSetType (可选配置)
FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为 unset (依赖驱动)-->
resultSetType="FORWARD_ONLY">


12

------------------------------------------------------------------------下面是针对select 的练手demo---------------------------------------------------------------------------------------

数据库:新增两张表(t_course, t_student)

t_course:



t_student:



其中,1个student可选择多个course进行学习。

我们还是拿上篇文章的demo, 继续写:

增加后,项目目录如下所示:



 

Course.java:



package com.dy.entity;

public class Course {

private int id;
private String name;
private int deleteFlag;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(int deleteFlag) {
this.deleteFlag = deleteFlag;
}

}


Student.java:



package com.dy.entity;

import java.util.List;

public class Student {

private int id;
private String idCard;
private String name;
private List<Course> courseList;
private int deleteFlag;

public Student(int id, String idCard, String name, List<Course> courseList, int deleteFlag) {
this.id = id;
this.idCard = idCard;
this.name = name;
this.courseList = courseList;
this.deleteFlag = deleteFlag;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Course> getCourseList() {
return courseList;
}
public void setCourseList(List<Course> courseList) {
this.courseList = courseList;
}
public int getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(int deleteFlag) {
this.deleteFlag = deleteFlag;
}
}


CourseDao.java:



package com.dy.dao;

import com.dy.entity.Course;

public interface CourseDao {

public Course findCourseById(int courseId);

}


StudentDao.java:



package com.dy.dao;

import com.dy.entity.Student;

public interface StudentDao {

public Student findStudentById(String idCard);
}


courseDao.xml:

<mapper namespace="com.dy.dao.CourseDao">

<!--
1.此处直接将resultType 设置为course, 一看就知道我设置了别名吧,如果没有设置别名,那么resultType = com.dy.entity.Course。
2.可能细心的你会发现:Course.java中的属性名与数据库字段名不一致,下面,我就在sql语句中用了as, 使之匹配,当然方法不止一种,
在学习了resultMap之后,你能看到一种更直观优雅的方式去将javabean中的属性与数据库字段名保持一致
3.findCourseById 与CourseDao中findCourseById方法对应, 那么传入的参数名称以及类型也应该保持对应关系。
4.可以看到,在sql语句中,通过#{}表达式可以获取参数。
5.下面这条sql语句,实际上的形式是怎么样的?还记得之前说过,mybatis默认为preparedStatement吧,那么,用我们jdbc代码来看,它其实就是:
select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=?
-->
<select id="findCourseById"  resultType="course" >
select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=#{courseId}
</select>

</mapper>


CourseDaoTest.java:



package com.dy.dao;

import java.io.IOException;

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.junit.Test;

import com.dy.entity.Course;

public class CourseDaoTest {

@Test
public void findCourseById() {
SqlSessionFactory sqlSessionFactory = getSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
Course course = courseDao.findCourseById(1);
}

//Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
private static SqlSessionFactory getSessionFactory() {
SqlSessionFactory sessionFactory = null;
String resource = "mybatis-conf.xml";
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsReader(resource));
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory;
}
}


上面的示例,我们针对course, 简单演示了 select的用法, 不过有个问题值得思考: 一个student可以对应多个course,  那么,在mybatis中如何处理这种一对多, 甚至于多对多,一对一的关系呢?

这儿,就不得不提到 resultMap 这个东西, mybatis的resultMap功能可谓十分强大,能够处理复杂的关系映射, 那么resultMap 该怎么配置呢? 别急,这就来了:

resultMap的配置:

<!--
1.type 对应类型,可以是javabean, 也可以是其它
2.id 必须唯一, 用于标示这个resultMap的唯一性,在使用resultMap的时候,就是通过id指定
-->
<resultMap type="" id="">

<!-- id, 唯一性,注意啦,这个id用于标示这个javabean对象的唯一性, 不一定会是数据库的主键(不要把它理解为数据库对应表的主键)
property属性对应javabean的属性名,column对应数据库表的列名
(这样,当javabean的属性与数据库对应表的列名不一致的时候,就能通过指定这个保持正常映射了)
-->
<id property="" column=""/>

<!-- result与id相比, 对应普通属性 -->
<result property="" column=""/>

<!--
constructor对应javabean中的构造方法
-->
<constructor>
<!-- idArg 对应构造方法中的id参数 -->
<idArg column=""/>
<!-- arg 对应构造方法中的普通参数 -->
<arg column=""/>
</constructor>

<!--
collection,对应javabean中容器类型, 是实现一对多的关键
property 为javabean中容器对应字段名
column 为体现在数据库中列名
ofType 就是指定javabean中容器指定的类型
-->
<collection property="" column="" ofType=""></collection>

<!--
association 为关联关系,是实现N对一的关键。
property 为javabean中容器对应字段名
column 为体现在数据库中列名
javaType 指定关联的类型
-->
<association property="" column="" javaType=""></association>
</resultMap>


好啦,知道resutMap怎么配置后,咱们立即接着上面的demo来练习一下吧:

------------------------------------------------------------------下面是用resultMap处理一对多关系的映射的示例-------------------------------------------------------------

一个student对应多个course, 典型的一对多,咱们就来看看mybatis怎么配置这种映射吧:

studentDao.xml:



<mapper namespace="com.dy.dao.StudentDao">

<!-- 这儿定义一个resultMap -->
<resultMap type="student" id="studentMap">

<!--
数据库中主键是id, 但是我这儿却是指定idCard为主键,为什么?
刚刚讲了,id用来表示唯一性, 我们可以认为只要idCard一样,那么他就是同一个学生。
如果此处用数据库中id, 那么mybatis将会认为数据库中每条记录都是一个student, 这显然不符合逻辑
-->
<id property="idCard" column="stu_id_card"/>
<result property="id" column="stu_id"/>
<result property="name" column="stu_name"/>
<result property="deleteFlag" column="stu_delete_flg"/>

<!--
这儿就是实现一对多的关键。
在Student中,courseList为List<Course>, 因此,ofType也应该与之对应(当然,我用了别名,不然要蛋疼的写全名了)。
collection的子标签是在指定Course的映射关系(由于Course的javabean的属性名与数据库的列名不一致)
-->
<collection property="courseList" column="stu_course_id" ofType="Course">
<id property="id" column="course_id"/>
<result property="name" column="course_name"/>
<result property="deleteFlag" column="course_delete_flg"/>
</collection>
</resultMap>

<!-- 这儿将返回类型设置成了上面指定的studentMap -->
<select id="findStudentById" resultMap="studentMap">
SELECT s.*, c.* FROM t_student s LEFT JOIN t_course c ON s.stu_course_id=c.course_id WHERE s.stu_id_card=#{idCard}
</select>

</mapper>


StudentDaoTest.java:



package com.dy.dao;

import java.io.IOException;
import java.util.List;

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.junit.Test;

import com.dy.entity.Course;
import com.dy.entity.Student;

public class StudentDaoTest {

@Test
public void findCourseById() {
SqlSessionFactory sqlSessionFactory = getSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
Student student = studentDao.findStudentById("20140101");
List<Course> courseList = student.getCourseList();
for (Course course: courseList) {
System.out.println(course.getId() + "   " + course.getName());
}
}

//Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
private static SqlSessionFactory getSessionFactory() {
SqlSessionFactory sessionFactory = null;
String resource = "mybatis-conf.xml";
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsReader(resource));
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory;
}
}


 

相信通过以上demo, 大家也能够使用mybatis的select 和 resultMap的用法了。上面demo只演示了一对多的映射,其实多对一、多对多也与它类似,所以我就没演示了,有兴趣的可以自己动手再做做。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: