mybaties的批量增刪改查及普通增刪改查

數據庫:html

create table school(
    id int(11) not null auto_increment comment '主鍵',
    name varchar(20) comment '學校名稱',
    address varchar(100) comment '學校地址',
    create_time datatime comment '數據上傳時間',
    primary key (id)
)

實體類:java

package com.test.entity;
public class School{
    private Integer id;//主鍵id
    private String name;//學校名稱
    private String address//學校地址
    private Date createTime//數據上傳時間
}

如今開始添加功能mysql

mybaties: schooMapper.xml:git

<mapper namespace="com.test.dao.SchoolMapper">
    <resultMap type="com.test.entity.School" id="schoolMap">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="address" property="address" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="DATE"/>
    </resultMap>
    <sql id="s_sql" >
        name,address,create_time
    </sql>
    
    <!-- 普通的插入數據不能返回id -->
    <insert id="save" parameterType="com.test.entity.School">
        insert into school (<include refid="s_sql"/>)values(#{name},#{address},#{createTime})
    </insert>
    
 </mapper>

    下面的能夠返回id,可是須要主鍵爲自增(id在這兒要不要均可以)github

<!-- 插入數據返回id,方法一  這個須要是自增的id -->
    <insert id="saveReturnIdOne" parameterType="com.test.entity.School" useGeneratedKeys="true" keyProperty="id">
        insert into school (id,<include refid="s_sql"/>)values(#{id},#{name},#{address},#{createTime})
    </insert>

這個第二種添加能夠返回主鍵id的,好像是返回添加的最後一個id--不須要自增(這個不確切知道)web

<!-- 插入數據返回id,方法一  這個返回最後添加的一條id -->
    <insert id="saveReturnIdTwo" parameterType="com.test.entity.School"                    useGeneratedKeys="true">
        insert into school (<include refid="s_sql"/>)values(#{name},#{address},#{createTime})
        <selectKey keyProperty="id"  resultType="int" order="AFTER" >
           SELECT LAST_INSERT_ID() AS VALUE
        </selectKey>
    </insert>

--------如今開始批量添加sql

<!-- 這個批量插入數據    -->
    <insert id="bathSave" parameterType="java.util.List">
        insert into school (<include refid="s_sql"/>)values
       <foreach collection="list" index="index" item="l" separator=",">
           (#{l.name},#{l.address},#{l.createTime})
       </foreach>
    </insert>

java代碼:數據庫

public int save(School test);
public int saveReturnIdOne(School test);
public int saveReturnIdTwo(School test); 
public void bathSave(List<School> list);

如今開始刪除功能mybatis

<!-- 這個普通刪除數據    -->
    <delete id="deleteById" parameterType="java.lang.Integer">
        delete from school where id=#{id}
    </delete>
    <!-- 這個批量刪除數據    -->
    <delete id="bathDelete" parameterType="java.util.List">
        delete from school where id in
        <foreach collection="list" index="index" item="l" open="(" close=")" separator=",">
            #{l}
        </foreach>
    </delete>
    <delete id="bathDeleteTwo" parameterType="java.util.List">

        delete from school where id in (${id})

    </delete>

java代碼:app

    public int deleteById(Integer list);
    public int bathDelete(List<Integer> list);
    public int bathDeleteTwo(Map<String,String>id);

如今開始修改功能

<!-- 普通修改      -->
<update id="update" parameterType="com.test.entity.School">
        update school set name=#{name}, address=#{address}, create_time=#{createTime} where id=#{id,jdbcType=INTEGER}
</update>
    <!-- 有選擇性的修改數據  -->
    <update id="updateSet" parameterType="com.test.entity.School">
        update school
        <set>
            <if test="name != null">
                name=#{name},
            </if>
            <if test="address !=null ">
                address=#{address},
            </if>
            <if test="createTime !=null ">
                create_time=#{createTime}
            </if>
        </set>
        where id=#{id}
    </update>
    <!--  這個批量修改須要在數據庫的url後面拼接 &allowMultiQueries=true 意思是同時執行多條,不然報錯  -->
    <update id="bathUpdate" parameterType="java.util.List">
        <foreach collection="list" index="index" item="l" open="" close="" separator=";">
            update school 
            <set>
                <if test="l.name != null">
                    name=#{l.name},
                </if>
                <if test="l.address !=null ">
                    address=#{l.address},
                </if>
                <if test="l.createTime !=null ">
                    create_time=#{l.createTime}
                </if>
            </set>
             where id=#{l.id,jdbcType=INTEGER}
        </foreach>
    </update> 
    
    <!--  還有一種批量修改多個id,即 id in(1,2,3,4) 方法類同批量刪除,這裏不寫了  -->

java代碼:

public void update(TestEntity test);
public void updateSet(TestEntity test);
public void bathUpdate(List<TestEntity> list);

如今開始查詢功能(批量查詢和刪除的同樣)

xml:

<!--  根據id查詢一條  -->
<select id="getById" resultMap="schoolMap" >
        select id,<include refid="s_sql"/> from school where id =#{id}
</select>
<!--  根據地址分頁查詢  -->
<select id="getLimit" resultMap="schoolMap" parameterType="java.util.Map">
    select id,<include refid="s_sql"/> from school where address=#{address} limit #{begin},#{end}
</select>
<!--  根據名字模糊查詢  -->
<select id="getLikeName" resultMap="schoolMap">
        select id,<include refid="s_sql"/> from school where name like concat('%',#{name},'%')
</select>
<!--  根據名字模糊查詢全部id集合  -->
<select id="getIdsLikeName" resultType="java.lang.String">
        select group_concat(id) from school  where name like concat('%',#{name},'%')
</select>
<!--  根據實體類屬性選擇查詢  -->
<select id="getWhere" resultMap="schoolMap">
        select id,<include refid="s_sql"/> from school
        <where>
            <if test="id != null">
                id=#{id}
            </if>
            <if test="name != null">
                and name=#{name}
            </if>
            <if test="address !=null ">
                and address=#{address}
            </if>
            <if test="createTime !=null ">
                and create_time=#{createTime}
            </if>
        </where>
</select>

java代碼:

public School getById(Integer id);
public List<School > getLimit(Map<String, Object> map);
public List<School > getLikeName(String name);
public String getIdsLikeName(String name);
public List<School > getWhere(School test);

 

下面是從其它地方看到:

同時執行多條sql的辦法:

 一、最簡單的辦法:在MySQL的鏈接字符串中設置allowMultiQueries參數置爲true。(只有MySQL Connector/J 3.1.1以上版本才支持) 。例如:在jdbc下設置鏈接字符串的時候設成以下的形式:
      jdbc:mysql://192.168.3.180/sample?user=root&password=&allowMultiQueries=true就能夠執行多條語句了
 在odbc下也是能夠設置的,方法以下:
設置 ODBC -- 配置 --Detials -- Flags 3 -- 鉤上 Allow multiple statements,這樣就能夠了。
結論:第一種方式最簡單。
二、在程序中對SQL語句以分號拆分紅多條SQL語句,而後使用Statement的addBatch方法,最後executeBatch就行。
但願對之後遇到此類問題的朋友有所幫助。

關於Statement的execute(String sql)語句可以同時執行多條SQL語句, 能夠看MySQL自帶的測試例子:

可查看testsuite.regression包下的ResultSetRegressionTest類:  這個能夠查看:MySQL for Java的SQL注入測試

 public class ResultSetRegressionTest extends BaseTestCase {    
    public void testBug33678() throws Exception {    
        if (!versionMeetsMinimum(4, 1)) {    
            return;    
        }    
        createTable("testBug33678", "(field1 INT)");    
        // allowMultiQueries=true設置    
        Connection multiConn = getConnectionWithProps("allowMultiQueries=true");    
        Statement multiStmt = multiConn.createStatement();    
        try {    
            multiStmt.setFetchSize(Integer.MIN_VALUE);    
            // 一次性執行多條SQL語句    
            multiStmt.execute("SELECT 1 UNION SELECT 2; INSERT INTO testBug33678 VALUES (1); UPDATE testBug33678 set field1=2; INSERT INTO testBug33678 VALUES(3); UPDATE testBug33678 set field1=2 WHERE field1=3; UPDATE testBug33678 set field1=2; SELECT 1");     
    // 如下代碼省略...    
    }    
}

 

 

還能夠查看英文API   Mapper XML Files

相關文章
相關標籤/搜索