框架简介:(来源百度百科)
iBATIS一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2002年发起的开放源代码项目。
于2010年6月16号被谷歌托管,改名为MyBatis。2013年11月迁移到Github。
资源下载
教程
http://mybatis.github.io/mybatis-3/zh/dynamic-sql.htmlMybatis jar包下载
http://www.mvnrepository.com/artifact/org.mybatis/mybatis/3.3.0基本API示例
1.创建配置文件(sqlMapConfig.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">
- <configuration>
- <!-- 数据源 -->
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/cs?characterEncoding=UTF-8"/>
- <property name="username" value="root"/>
- <property name="password" value="root"/>
- </dataSource>
- </environment>
- </environments>
- <!-- 映射配置文件 -->
- <mappers>
- <mapper resource="Students.xml"/>
- </mappers>
- </configuration>
2.获取MyBatis sql会话对象
- public static SqlSession getSession() throws IOException{
- String cf = "sqlMapConfig.xml";
- InputStream inputStream = Resources.getResourceAsStream(cf);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- return sqlSessionFactory.openSession();
- }
3.创建映射配置文件(Students.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="com.wwq.test.Students">
- <!-- 复用的公共部分 -->
- <sql id="cols">
- id,name,age,pass,score
- </sql>
- <sql id="table">
- <span style="white-space:pre"> </span>students
- </sql>
- <sql id="inserVals">
- #{id, jdbcType=INTEGER},
- #{name, jdbcType=VARCHAR},
- #{age, jdbcType=INTEGER},
- #{pass, jdbcType=BOOLEAN},
- #{score, jdbcType=DOUBLE}
- </sql>
- <sql id="updateVals">
- set name = #{name, jdbcType=VARCHAR},
- age = #{age, jdbcType=INTEGER},
- pass = #{pass, jdbcType=BOOLEAN},
- score = #{score, jdbcType=DOUBLE}
- </sql>
- <!-- 查询 -->
- <select id="findAll_stu" resultType="com.wwq.test.bean.Students">
- SELECT <include refid="cols"/> FROM <include refid="table"/>
- </select>
- <!-- 插入 -->
- <insert id="insert_stu" useGeneratedKeys="true" keyProperty="id">
- INSERT INTO <include refid="table"/> ( <include refid="cols"/> ) VALUES ( <include refid="inserVals" />);
- </insert>
- <!-- 修改 -->
- <update id="update_stu">
- UPDATE <include refid="table"/> <include refid="updateVals"/>
- </update>
- <!-- 删除 -->
- <delete id="delete_stu" parameterType="com.wwq.test.bean.Students">
- DELETE FROM <include refid="table"/>
- </delete>
- </mapper>
4.创建数据模型Bean
- public class Students{
- private Integer id;
- private String name;
- private Integer age;
- private Boolean pass;
- private Double score;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public Boolean getPass() {
- return pass;
- }
- public void setPass(Boolean pass) {
- this.pass = pass;
- }
- public Double getScore() {
- return score;
- }
- public void setScore(Double score) {
- this.score = score;
- }
- }
5.调用相应的API
- /*保存:返回影响的行数*/
- public static void save() throws IOException, InterruptedException{
- Students llj = new Students("李连杰", 45, true, 92.5);
- SqlSession session = getSession();
- int number = session.insert("insert_stu",llj);
- System.out.println(String.format("主键:%1$s", llj.getId()));
- System.out.println(String.format("插入的行数:%1$s", number));
- session.commit();
- }
- /*删除:返回影响的行数*/
- public static void del()throws IOException, InterruptedException{
- SqlSession session = getSession();
- Students stu = new Students();
- stu.setId(15);
- int number = session.delete("delete_stu",stu);
- session.commit();
- System.out.println(String.format("删除的行数:%1$s", number));
- }
- /*修改:返回影响的行数*/
- public static void update()throws IOException,InterruptedException{
- Students stu = new Students(true);
- SqlSession session = getSession();
- int number = session.update("update_stu",stu);
- session.commit();
- System.out.println(String.format("更新的行数:%1$s", number));
- }
- /*没有记录返回,一个空的集合(不是null)*/
- public static List<Students> findAll() throws IOException, InterruptedException{
- SqlSession session = getSession();
- List<Students> stus = session.selectList("findAll_stu");
- System.out.println(stus);
- return stus;
- }
- /*使用selectOne API查询,结果多条会报异常:Expected one result (or null) to be returned by selectOne(), but found: 2*/
- public static Students findOne() throws IOException, InterruptedException{
- SqlSession session = getSession();
- Students stu = session.selectOne("findAll_stu");
- return stu;
- }
- /*RowBounds:指定检索范围,他是在查询结果之上再次进行范围筛选*/
- public static List<Students> findBounds()throws IOException, InterruptedException{
- SqlSession session = getSession();
- RowBounds rowBounds = new RowBounds(0, 2);
- List<Students> stus = session.selectList("findAll_stu", null, rowBounds);
- System.out.println(stus);
- return stus;
- }
- /*selectMap:将返回的列表转换成以某列值为key的map*/
- public static Map<Integer, Students> findMap()throws IOException, InterruptedException{
- SqlSession session = getSession();
- Map<Integer, Students> selectMap = session.selectMap("findAll_stu", "id");
- System.out.println(selectMap);
- return selectMap;
- }
动态SQL示例
1.增加动态SQL映射配置
- <!-- ############### 动态SQL ############### -->
- <!-- if -->
- <delete id="delete_dynamic_if" parameterType="java.lang.Integer">
- DELETE FROM <include refid="table"/> WHERE
- <if test="id!=null and id!=''"> id = #{id,jdbcType=INTEGER}</if>
- <if test="name!=null and name!=''"> AND name LIKE #{id,jdbcType=INTEGER}</if>
- </delete>
- <!-- choose -->
- <delete id="delete_dynamic_choose" parameterType="java.lang.Integer">
- DELETE FROM <include refid="table"/> WHERE
- <choose>
- <when test="score>60">age < 25</when>
- <otherwise>age > 25 </otherwise>
- </choose>
- </delete>
- <!-- where -->
- <select id="delete_dynamic_where" parameterType="java.lang.Integer">
- SELECT * FROM <include refid="table"/>
- <where>
- <if test="id!=null and id!=''"> id = #{id,jdbcType=INTEGER}</if>
- <if test="name!=null and name!=''"> AND name LIKE #{id,jdbcType=INTEGER}</if>
- </where>
- </select>
- <!-- set -->
- <update id="delete_dynamic_set">
- UPDATE <include refid="table"/>
- <set>
- <if test="name!=null and name!=''">name = #{name, jdbcType=VARCHAR},</if>
- <if test="age!=null and age!=''">age = #{age, jdbcType=INTEGER},</if>
- <if test="pass!=null and pass!=''">pass = #{pass, jdbcType=BOOLEAN},</if>
- <if test="pass!=null and pass!=''">score = #{score, jdbcType=DOUBLE}</if>
- </set>
- </update>
- <!-- trim -->
- <delete id="delete_dynamic_trim">
- DELETE FROM <include refid="table"/>
- <trim prefix="WHERE" prefixOverrides="AND | OR ">
- <if test="name!=null and name!=''">AND name = #{name, jdbcType=VARCHAR}</if>
- <if test="age!=null and age!=''">AND age = #{age, jdbcType=INTEGER}</if>
- <if test="pass!=null and pass!=''">OR pass = #{pass, jdbcType=BOOLEAN}</if>
- <if test="pass!=null and pass!=''">AND score = #{score, jdbcType=DOUBLE}</if>
- </trim>
- </delete>
- <update id="delete_dynamic_trim2">
- UPDATE <include refid="table"/>
- <trim prefix="SET" suffix="," suffixOverrides=",">
- <if test="name!=null and name!=''">name = #{name, jdbcType=VARCHAR}</if>
- <if test="age!=null and age!=''">age = #{age, jdbcType=INTEGER}</if>
- <if test="pass!=null and pass!=''">pass = #{pass, jdbcType=BOOLEAN}</if>
- <if test="pass!=null and pass!=''">score = #{score, jdbcType=DOUBLE}</if>
- </trim>
- </update>
- <!-- foreach:集合取值形参必须是list -->
- <select id="findAll_dynamic_foreach" resultType="com.wwq.test.bean.Students">
- SELECT * FROM <include refid="table"/>
- <if test="list!=null and list.size() > 0">
- WHERE id IN
- <foreach item="stu" index="index" collection="list" open="(" separator="," close=")">
- #{stu.id}
- </foreach>
- </if>
- </select>
2.调用相应的API
- /*动态sql:foreach*/
- public static List<Students> findAllDynamicForeach()throws IOException, InterruptedException{
- SqlSession session = getSession();
- List<Students> stus = new ArrayList<Students>();
- stus.add(new Students(16));
- stus.add(new Students(18));
- List<Students> ruts = session.selectList("findAll_dynamic_foreach",stus);
- return ruts;
- }
关联映射示例
1.在数据模型Bean中增加关联实体。
- public class Students{
- .......
- private Role role;
- private List<ClassAndGrade> cgs;
- public List<ClassAndGrade> getCgs() {
- return cgs;
- }
- public void setCgs(List<ClassAndGrade> cgs) {
- this.cgs = cgs;
- }
- public Role getRole() {
- return role;
- }
- public void setRole(Role role) {
- this.role = role;
- }
- ........
- }
2.增加映射文件
- <!-- 关联嵌套查询 -->
- <resultMap id="resStu" type="com.wwq.test.bean.Students">
- <association property="role" column="role_id" javaType="com.wwq.test.bean.Role" select="selectRole"/>
- </resultMap>
- <select id="find_ResStu" resultMap="resStu">
- SELECT * FROM students
- </select>
- <select id="selectRole" resultType="com.wwq.test.bean.Role">
- SELECT * FROM role WHERE id = #{id}
- </select>
- <!-- 关联嵌套结果 -->
- <resultMap id="resStuResults" type="com.wwq.test.bean.Students">
- <association property="role" javaType="com.wwq.test.bean.Role">
- <id property="id" column="role_id"/>
- <result property="name" column="role_name"/>
- </association>
- </resultMap>
- <select id="find_ResStu_results" resultMap="resStuResults">
- SELECT s.id,s.name,age,pass,score,role_id,r.name role_name
- FROM students s LEFT JOIN role r ON s.role_id = r.id;
- </select>
- <!-- 集合的嵌套查询 -->
- <resultMap id="resStuColl" type="com.wwq.test.bean.Students">
- <collection property="cgs" javaType="ArrayList" column="id" ofType="com.wwq.test.bean.ClassAndGrade" select="find_cgs_select"/>
- </resultMap>
- <select id="find_Res_Stu_Coll" resultMap="resStuColl">
- SELECT * FROM students
- </select>
- <select id="find_cgs_select" resultType="com.wwq.test.bean.ClassAndGrade">
- SELECT * FROM classandgrade cg
- LEFT JOIN stu_cg sc ON cg.id = sc.cg_id
- WHERE sc.stu_id = #{id};
- </select>
- <!-- 集合的嵌套结果 -->
- <resultMap id="resStuResultsColl" type="com.wwq.test.bean.Students">
- <collection property="cgs" ofType="com.wwq.test.bean.ClassAndGrade" >
- <result column="cg_id" property="id"/>
- <result column="cg_name" property="name"/>
- </collection>
- </resultMap>
- <select id="find_Res_Stu_Coll_Results" resultMap="resStuResultsColl">
- SELECT s.id,s.name,age,pass,score,role_id,r.name role_name,cg.id as cg_id,cg.name as cg_name
- FROM students s
- LEFT JOIN role r ON s.role_id = r.id
- LEFT JOIN stu_cg sc ON sc.stu_id = s.id
- LEFT JOIN classandgrade cg ON cg.id = sc.cg_id;
- </select>
打印映射的SQL
1.导入Log4j的jar包。
2.编写Log4j配置文件
- # Global logging configuration
- log4j.rootLogger=ERROR, stdout
- # MyBatis logging configuration...
- log4j.logger.com.wwq.test.Students=TRACE
- # Console output...
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
完整示例:MyBatis 练习 (http://download.youkuaiyun.com/detail/javamr_wwq/9246761)