簡體   English   中英

如何使用myBatis中的selectKey一次在2個表中插入數據

[英]how to insert data in 2 tables at a time using selectKey in myBatis

我需要使用myBatis select鍵和Java將數據存儲在2個表中,任何人都可以幫忙做到這一點。我的表結構是:

     Temp                                          Sect
id name created_at                           sid  sectName  duration   priorty

現在我需要在Temp和Sect表中插入name,sectName,duration,priority,我寫的代碼是:

@Insert("insert into Temp (name) values(#{name})")
@SelectKey(statement="call identity()", keyProperty="id", before=false, 
resultType=int.class)
public int insertTemp(Name name);

@Insert("insert into sect (name,duration.priority) values(#{name}, #
{duration},#{priority})")
@SelectKey(statement="call next value for TestSequence", 
keyProperty="nameId", before=true, resultType=int.class)
public int insertSect(sectName name);

我的POJO類是:

Public Temp{
  private int id;
  private String name;
  private int creat_at;
  //setters getters
}

Public Temp{
  private int sid;
  private String sectName;
  private int duration;
  private int priority;
  //setters getters
}

請有人告訴我如何編寫該查詢,而我編寫的命令是正確還是錯誤?

您的模型有點令人困惑。 我假設第二個Temp應該被命名為“ Sect”

您實際上在insertSect中使用標志before = true。 您可以這樣使用:

//First insert into db
@Insert("insert into sect (**id**, name,duration.priority) values(**#{id}**, #{name}, #
{duration},#{priority})")
(...)
public int insertSect(sectName name);

//second insert
@Insert("insert into Temp (**id**, name) values(**#{id}**, #{name})")
//there's no select key anymore
public int insertTemp(**@Param("name")** Name name, **@Param("id") id**);

//and calling it
mapper.insertSect(sect)
sect.getId() //will return ID returned by "call next value for TestSequence"
mapper.insertTemp(name, sect.getId())

“ **”字符用於引起您對代碼更改的注意。 不幸的是,所以不要在代碼部分中加粗文本。

如果插入后不需要在多個對象中創建ID,也可以使用一個插入。

@Insert("insert into Temp(id, name) values (#{sect.id}, #{name});
insert into Sect(id, name, ...) values (#{sect.id}, #{sect.name}, ...)")
@SelectKey(statement="call next value for TestSequence", 
keyProperty="sect.id", before=true, resultType=int.class)
public void insert(@Param("sect") Sect sect, @Param("name") String name)

如果需要使用兩個不同的鍵,則最好的方法是使用一個方法,該方法將調用兩個插入並將其注釋為@Transcational,因此第二個插入失敗將回滾第二次,例如

@Transactional
void insert(...) {
    mapper.firstInsert(...)
    mapper.secondInsert(...)
}

如果不是您想要的,請澄清-現在您的問題(和型號)有些混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM