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

jopen 9年前發布 | 59K 次閱讀 mybaties MyBatis3 持久層框架

數據庫:

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)
)

實體類:

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

現在開始添加功能

mybaties: schooMapper.xml:

<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在這兒要不要都可以)

<!-- 插入數據返回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--不需要自增(這個不確切知道)

<!-- 插入數據返回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>

--------現在開始批量添加

<!-- 這個批量插入數據    -->
    <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);

現在開始刪除功能

<!-- 這個普通刪除數據    -->
    <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>

java代碼:

    public int deleteById(Integer list);
    public int bathDelete(List<Integer> list);

現在開始修改功能

<!-- 普通修改      -->
<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的辦法:

 1、最簡單的辦法:在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,這樣就可以了。
結論:第一種方式最簡單。
2、在程序中對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

來自:http://my.oschina.net/u/2297250/blog/373296

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!