1. 程式人生 > >MyBatis增刪改查操作Demo

MyBatis增刪改查操作Demo

  • 第一步:導包:mybatis及jdbc connector.jar
  • 第三步:配置表和類的對映檔案,實體類名.xml(在裡面寫sql語句)
  • 第四步:建立資料庫會話session,進行增刪改查

檔案目錄 這裡寫圖片描述

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration
>
<!-- 可以給實體類取別名,這個放在前面,放在後面會出錯 --> <typeAliases> <typeAlias type="com.test.entity.Student" alias="Student"/> </typeAliases> <!-- step1:配環境 --> <environments default="e1"> <environment id="e1"> <!-- 先配事務,事務是必須配的,簡單的事務型別JDBC -->
<transactionManager type="JDBC"></transactionManager> <!-- 再配資料來源,POOLED 以連線池的方式 --> <dataSource type="POOLED"> <!-- 在資料來源中配置連線屬性,注意這裡是username不是user --> <property name="driver" value="com.mysql.jdbc.Driver"
/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root1205"/> </dataSource> </environment> </environments> <!-- step2:引入實體類的對映配置檔案 --> <mappers> <mapper resource="com/test/entity/Student.xml"/> </mappers> </configuration>

Student.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD SQL Map 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<!-- 名稱空間必須要加上,解決sql語句id重複 -->
<mapper namespace="ns1">
<!-- 插入資料 -->
    <!-- 寫死的 -->
    <insert id="save">
    insert into student(name,age)values('一茶',18)    
    </insert>
    <!-- 使用佔位符,不是問號了,其中id,name指的是session的insert方法所傳物件引數的屬性 -->
    <insert id="save2">
    insert into student(name,age)values(#{name},#{age})
    </insert>
    <insert id="save3">
    insert into student(name,age)values(#{name},#{age});
    </insert>
<!-- 修改資料 -->
    <update id="mod1">
    update student set name='王五',age='10' where id=1
    </update>
    <update id="mod2">
    update student set name=#{name},age=#{age} where id=1
    </update>
<!-- 刪除資料 -->
    <delete id="del1">
    delete from student where id=1
    </delete>
    <delete id="del2">
    delete from student where name=#{name} and age=#{age}
    </delete>
<!-- 查詢資料 -->
    <!-- ExecutorException:excIt's likely that neither a Result Type nor a Result Map was specified. -->
    <!-- 預設會自動對映,所以resultMap可以不配,如果要自定義對映要配置resultMap -->
    <!-- 可以給com.test.entity.Student配別名,在SqlMapConfig裡配typeAliases -->
    <!-- <select id="query1" resultType="com.test.entity.Student"> -->
    <select id="query1" resultType="Student">
    select * from student where id=2    
    </select>
    <select id="query2" resultType="Student">
    select * from student where name=#{name}
    </select>
    <select id="query3" resultType="Student" parameterType="java.lang.String">
    select * from student where name=#{_parameter}
    </select>
    <select id="query4" resultType="Student" parameterType="int">
    select * from student where id=#{_parameter}
    </select>
    <!-- 預設是自動對映,還可以自定義對映,要配置resultMap -->
    <resultMap type="Student" id="myMap">
        <!-- 雖然我只映射了一個表字段,但剩下的欄位會按預設情況對映 -->
        <result property="name" column="name2"/>
    </resultMap>
    <select id="query5" resultType="Student" resultMap="myMap">
    select name as name2,age,school from student where id=#{_parameter}
    </select>
    <select id="query6" resultType="Student">
    select * from student where 1=1
    </select>
    <select id="query7" resultType="Student" parameterType="java.lang.String">
    select * from student where name=#{_parameter}
    </select>
    <select id="query8" resultType="Student">
    select * from student where 1=1
    </select>
    <select id="query9" resultType="Student" parameterType="java.lang.String">
    select * from student where name=#{_parameter}
    </select>   
</mapper>

TestDemo.java

package com.test.test;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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 com.test.entity.Student;

public class TestDemo {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // 測試能否連線資料庫,並插入資料
        //第一步:和資料庫連線(獲取與資料庫會話物件)
        SqlSession session = null;
        SqlSessionFactory sessionFactory = null;
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
        sessionFactory = factoryBuilder.build(reader);
        session = sessionFactory.openSession();
        //System.out.println(session);//測試是否連線成功

        //第二步:和資料庫互動
        //op1:插入資料
        //session.insert("ns1.save");
        //Map map = new HashMap();
        //map.put("name", "zhangsan");
        //map.put("age", "18");//此處的18雖然是字串,但是也按int插入到age欄位裡了
        //session.insert("ns1.save2",map);
        //Student stu = new Student();
        //stu.setAge(20);
        //stu.setName("lisi");
        //session.insert("ns1.save3", stu);

        //op2:修改資料
        //session.update("ns1.mod1");
        //Student stu2 = new Student();
        //stu2.setAge(20);
        //stu2.setName("lisi2");
        //session.update("ns1.mod2", stu2);

        //op3:刪除資料
        //session.delete("ns1.del1");
        //Student stu3 = new Student();
        //stu3.setAge(20);
        //stu3.setName("lisi");
        //session.delete("ns1.del2",stu3);

        //op4:查詢資料
        //selectOne
        Student sd1 = session.selectOne("ns1.query1");
        System.out.println(sd1.getName());
        System.out.println(sd1.getAge());
        Map map2 = new HashMap();
        map2.put("name", "張三");
        //傳一個引數這樣傳太費勁了,name='張三'有兩條資料,selectOne返回的結果只能是null或一條,所以此時報異常
        //Expected one result (or null) to be returned by selectOne(), but found: 2
        //System.out.println(session.selectOne("ns1.query2",map2));
        //直接傳字串,需要制定parameterType以及佔位符用_parameter
        Student sd3 = session.selectOne("ns1.query3","馬冬梅");
        System.out.println(sd3.getAge());
        Student sd4 = session.selectOne("ns1.query4", new Integer(11));
        System.out.println(sd4.getName());
        Student sd5 = session.selectOne("ns1.query5", new Integer(11));
        System.out.println(sd5.getName());
        System.out.println(sd5.getAge());
        System.out.println(sd5.getSchool());
        //selectList
        List<Student> sList = session.selectList("ns1.query6");
        for(Student s:sList){
            System.out.println(s.getName()+","+s.getAge());
        }
        List<Student> sList2 = session.selectList("ns1.query7", "張三");
        for(Student s:sList2){
            System.out.println(s.getName()+","+s.getAge());
        }
        //selectMap
        //selectMap(String s1,String s2)返回的結果是以指定列s2為key,以Bean為value的map
        Map<Integer,Student> map = session.selectMap("ns1.query8","id");
        Set<Integer> k = map.keySet();
        Iterator<Integer> it = k.iterator();
        while(it.hasNext()){
            int key = it.next();
            System.out.print(key+"-----"+map.get(key).getId());
            System.out.print(","+map.get(key).getName());
            System.out.print(","+map.get(key).getAge());
            System.out.println(","+map.get(key).getSchool());
        }
        //selectMap(String s1,Object obj,String s2)返回的結果是以指定列s2為key,以Bean為value的map
        Map<Integer,Student> map3 = session.selectMap("ns1.query9", "張三", "id");
        Set<Integer> k3 = map3.keySet();
        Iterator<Integer> it3 = k3.iterator();
        while(it3.hasNext()){
            int key = it3.next();
            System.out.print(key+"-----"+map3.get(key).getId());
            System.out.print(","+map3.get(key).getName());
            System.out.print(","+map3.get(key).getAge());
            System.out.println(","+map3.get(key).getSchool());
        }

        //必須寫提交,不會預設提交的,此處不寫,不會提交到資料庫
        session.commit();

    }

}