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

jopen 9年前

数据库:

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