1. 程式人生 > 程式設計 >Mybatis批量插入返回成功的數目例項

Mybatis批量插入返回成功的數目例項

Mybatis批量插入返回影響的行數

環境:

postgresql 9.6.5

spring 4.1

mybatis3

junit4

log4j

ThesisMapper.xml:

<!-- 批量插入 -->
  <insert id="insertList" parameterType="java.util.List">
    insert into public.thesis
    (name)
    values
    <foreach collection="list" item="t" index="index" separator=",">
      (
      #{t.name}
      )
    </foreach>
  </insert>

Mapper.java 藉口:

public interface ThesisMapper {
  int insertList(List<Thesis> thesisList);
}

服務類:

ThesisService:

public int insertList(List<Thesis> thesisList) throws Exception {
  return thesisDao.insertList(thesisList);
}

測試父類:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-mvc.xml","classpath:spring-mybatis.xml" })
@WebAppConfiguration
public class BaseTest {
  @Autowired
  protected WebApplicationContext wac;
  @Test
  public void test() {}
}

測試類:

public class UserOpsTest extends BaseTest {
  @Autowired
  private ThesisService ts;
  @Test
  public void insertListTest() {
    List<Thesis> thesisList = new ArrayList<Thesis>();
    Thesis t1 = new Thesis();
    Thesis t2 = new Thesis();
    Thesis t3 = new Thesis();
    t1.setName("qq1");
    t2.setName("ww2");
    t3.setName("asd");
    thesisList.add(t1);
    thesisList.add(t2);
    thesisList.add(t3);
    try {
      System.out.println(ts.insertList(thesisList));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

日誌輸出:

[DEBUG] ==> Preparing: insert into public.thesis ( name) values ( ? ) 
 [DEBUG] ==> Parameters: qq1(String),ww2(String),asd(String)
 [DEBUG] <==  Updates: 3
 3

返回結果既為所求.

原始碼地址:

https://github.com/timo1160139211/trans

補充:關於Mybatis的insert方法返回值(將返回值受影響條數改為插入後的自增主鍵id)

今天做ssm專案的時候有一個這樣的需求——我借閱一本書然後生成一條借閱記錄(借閱記錄的主鍵是遞增的“borrowNum”),然後將這條記錄的主鍵返回,在往上查閱資料後知道,只要在對應的xml檔案對應的那個方法加上兩個屬性就行了,程式碼如下:

 <insert id="insert" parameterType="com.bsm.model.Borrow" useGeneratedKeys="true" keyProperty="borrownum" keyColumn="borrowNum" >
  insert into t_borrow (userAccount,bookInfoNum,borrowTime,giveBackTime)
  values (#{useraccount,jdbcType=VARCHAR},#{bookinfonum,jdbcType=INTEGER},#{borrowtime,jdbcType=DATE},#{givebacktime,jdbcType=DATE})
 </insert>

就是加入的這三個屬性:

useGeneratedKeys="true" keyProperty="borrownum" keyColumn="borrowNum"

Mybatis 配置檔案 useGeneratedKeys 引數只針對 insert 語句生效,預設為 false。當設定為 true 時,表示如果插入的表以自增列為主鍵,則允許 JDBC 支援自動生成主鍵,並可將自動生成的主鍵返回。

“keyProperty”的值對應入參的欄位名,“keyColumn”的值對應資料庫表中的列名。

Mybatis批量插入返回成功的數目例項

入參欄位:

Mybatis批量插入返回成功的數目例項

但是我們想接收這個返回的id的時候卻不是我們想要的

int i=borrowMapper.insert(borrow);

我們得到的還是受影響的條數而不是返回的borrownum的值,那我們返回的borrownum去哪裡了呢?在這裡:我們的入參是不是一個borrow?

int mun=borrow.getBorrownum();

這個返回的mun就是我們要的borrownum了,原來這個返回的值放進了入參的那個物件中。

資料庫欄位:

Mybatis批量插入返回成功的數目例項

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。