mybatis學習(一)不使用 XML 構建 SqlSessionFactory


 

 

如果使用 Maven 來構建項目,則需將下面的 dependency 代碼置於 pom.xml 文件中:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>

配置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">
<configuration>

      <!-- 別名 
        1.類型別名 typeAlias type屬性值為全類名 alias為別名
        2.根據包   name屬性值為包名 別名為包內類名的小寫
      -->
    <typeAliases>
        <!-- <typeAlias type="com.tzh.bean.Clazz" alias="clazz"/>
        <typeAlias type="com.tzh.bean.Student" alias="student"/> -->
        <package name="com.tzh.bean"/>
    </typeAliases>

    <environments default="default">
        <environment id="default">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql:///1606a" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/tzh/mapper/*.xml" />
    </mappers>

</configuration>

創建beanSession工廠

每個基於 MyBatis 的應用都是以一個 SqlSessionFactory 的實例為核心的。SqlSessionFactory 的實例可以通過 SqlSessionFactoryBuilder 獲得。而 SqlSessionFactoryBuilder 則可以從 XML 配置文件或一個預先定制的 Configuration 的實例構建出 SqlSessionFactory 的實例。
package com.tzh.test;

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;

public class SqlSessionUtils {

    public static SqlSession getSqlSession() {
        SqlSession sqlSession = null; try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");

            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

            sqlSession = sqlSessionFactory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

創建mapper接口

package com.tzh.mapper;

import java.util.List;

import com.tzh.bean.Student;

public interface StuMapperDao {
    
    List<Student> getStuList(Student student);
    List<Student> getStuListChoose(Student student);
    
    int updateStu(Student student);
    
    int addStu(List<Student> stuList );
    

    int delStu(int [] arr);
}

sql語句

<?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="namespace">
     <!-- student為別名 在核心配置文件設置 -->
    <select id="getStuList" resultType="student" parameterType="student">

        select * from 0802_stu
        <!-- where 1 = 1 -->
        <!-- 如果內部的判斷條件成立,會自動加上where關鍵字,並且會把多余的and或者or去掉 -->
        <where>
            <if test="sname !=null and sname!='' ">
                and sname like concat('%',#{sname},'%')
            </if>

            <if test="sex!=null and sex!=''">
                and sex =#{sex}
            </if>
            <if test="age >0 ">
                and age &lt; #{age}
            </if>
        </where>
    </select>
    <select id="getStuListChoose" resultType="student"
        parameterType="student">

        select * from 0802_stu
        <!-- where 1 = 1 -->
        <!-- 如果內部的判斷條件成立,會自動加上where關鍵字,並且會把多余的and或者or去掉 -->
        <!-- <where> -->
        <trim prefix="where" prefixOverrides="and |or ">
            <!-- 條件成立在前面加上WHER關鍵詞 並 prefixOverrides前綴覆蓋 條件成立去挑前綴add|or-->

            <!-- choose when otherwise 用法和switch case break 類似 只運行一個條件都符合時運行第一個 -->
            <choose>
                <when test="sname !=null and sname!='' ">
                    and sname like concat('%',#{sname},'%')
                </when>
                <when test="sex!=null and sex!=''">
                    and sex =#{sex}
                </when>
                <otherwise><!-- 其他相當於else -->
                    and age &lt; #{age}
                </otherwise>
            </choose>
        </trim>
        <!-- </where> -->
    </select>

    <update id="updateStu" parameterType="student">
        update 0802_stu
        <!-- SET 在內部的條件成立,就會加上set關鍵字,並且會把多余的逗號去掉 -->
        <!-- <set> -->
        <trim prefix="set" suffixOverrides=",">
        <!-- suffixOverrides 去掉多余的 , -->
            <if test="sname != null and sname !=''">
                sname = #{sname},
            </if>
            <if test="sex !=null and sex != ''">
                sex = #{sex},
            </if>
            <if test="age>0">
                age = #{age}
            </if>
            </trim>
        <!-- </set> -->
        where sid= #{sid}
    </update>
    
    <insert id="addStu" parameterType="list">
        INSERT into 0802_stu (sname,sex,age,cid) VALUES 
        <!-- 你可以傳遞一個 List 實例或者數組作為參數對象傳給 MyBatis。
        當你這么做的時 候,MyBatis 會自動將它包裝在一個 Map 中,用名稱在作為鍵。
        List 實例將會以“list” 作為鍵,而數組實例將會以“array”作為鍵。 -->
        <foreach collection="list" item="stu" separator=",">
            (#{stu.sname},#{stu.sex},#{stu.age},#{stu.cid})
        </foreach>
        
                <!-- ('隆多','',20,2),
                ('隆多','',20,2),
                ('隆多','',20,2),
                ('隆多','',20,2),
                ('隆多','',20,2),
                ('隆多','',20,2) -->
    
    </insert>
    
    <delete id="delStu" parameterType="java.lang.reflect.Array">
        DELETE FROM 0802_stu WHERE sid in 
            <foreach collection="array" item="sid" open="("  separator=","  close=")" >
                #{sid}
            </foreach>
    </delete>

</mapper>

測試

package com.tzh.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.tzh.bean.Student;
import com.tzh.mapper.StuMapperDao;

public class TestDemo {
    
    @Test
    public void testListLike() {
        
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
        Student student = new Student();
        student.setSname("k");
        student.setSex("");
        student.setAge(34);
        
        //List<Student> stuList = mapper.getStuList(student);
        List<Student> stuList = mapper.getStuListChoose(student);
        for (Student student2 : stuList) {
            System.out.println(student2);
        }
        
        
    }
    
    @Test
    public void testUpdate() {
        
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
        Student student = new Student();
        student.setSname("k");
        student.setSex("");
        //student.setAge(34);
        student.setSid(1);
        
        int updateStu = mapper.updateStu(student);
        sqlSession.commit();
    }
    
    @Test
    public void testAdd() {
        
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
        Student student = new Student();
        student.setSname("k");
        student.setSex("");
        student.setAge(34);
        student.setCid(1);
        Student student1 = new Student();
        student1.setSname("k");
        student1.setSex("");
        student1.setAge(34);
        student1.setCid(1);
        Student student2 = new Student();
        student2.setSname("k");
        student2.setSex("");
        student2.setAge(34);
        student2.setCid(1);
        
        List<Student> stuList = new ArrayList<Student>();
        
        stuList.add(student);
        stuList.add(student1);
        stuList.add(student2);
        
        int addStu = mapper.addStu(stuList);
        
        sqlSession.commit();
        
    }
    
    @Test
    public void testDel() {
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
        
        int [] arr = {1,2,3,4,5};
        
        int delStu = mapper.delStu(arr);
        sqlSession.commit();
    }

}

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM