以下代碼無法可靠地創建新記錄。EntityManager.merge()不創建表記錄
TransferRecord transfer = new TransferRecord();
transfer.setTransferId(metaData.getTransferId());
transfer.setUserName(metaData.getUserId().getUserName());
transfer.setCancelled(false);
em.merge(transfer);
em.flush();
下面是轉移記錄代碼:
/***
* Contains a record of an ongoing transfer.
* @author anchapma
*
*/
@Entity
@Table(name = "TransferRecord")
public class TransferRecord implements Serializable
{
/**
* Generated static unique ID.
*/
private static final long serialVersionUID = -8131586518447878482L;
/***
* The id of the transfer.
*/
private String transferId;
/***
* The name of the user who ownes the transfer.
*/
private String username;
/***
* Has this transfer been cancelled?
*/
private boolean cancelled;
/***
* Constructor.
*/
public TransferRecord()
{
this.transferId = "";
this.username = "";
this.cancelled = false;
}
/***
* Gets the transfer ID.
*
* @return The transfer ID.
*/
@Id
@Column(name = "TransferID", unique = true, nullable = false, length = 50)
public String getTransferId()
{
return this.transferId;
}
/***
* Sets the transfer ID.
* @param transferId The new transfer ID.
*/
public void setTransferId(String transferId)
{
this.transferId = transferId;
}
/***
* Gets the username.
*
* @return The username.
*/
@Column(name = "UserName", nullable = false, length = 50)
public String getUserName()
{
return this.username;
}
/***
* Sets the username.
* @param username The new username.
*/
public void setUserName(String username)
{
this.username = username;
}
/***
* Gets whether or not the transfer has been cancelled.
*
* @return True if the transfer has been cancelled.
*/
@Column(name = "Cancelled", nullable = false, length = 50)
public boolean getCancelled()
{
return this.cancelled;
}
/***
* Sets whether or not the transfer has been cancelled.
* @param cancelled True if the transfer has been cancelled.
*/
public void setCancelled(boolean cancelled)
{
this.cancelled = cancelled;
}
}
我認爲,正在發生的事情是一條記錄被延遲一段時間後加入到數據庫中。我的代碼使用TransferRecord記錄的存在或不存在作爲標誌。因此它需要數據立即顯示在表格中。
我可能是正確的我的假設?如果是這樣,有沒有辦法強制em.flush()
調用等待,直到它返回前寫出記錄?
你的一些陳述非常模糊。例如,「因此它需要數據立即顯示在表格中。」從交易的角度來看沒什麼意義。 'em.flush()'將導致持久化上下文被刷新到數據庫;不同事務中這些更改的可見性受事務隔離級別的限制。因此,說出你想要的行爲是值得的。另外,「有沒有辦法強制em.flush()調用等到它在返回之前寫出記錄?」沒有任何意義,因爲它是一個阻塞呼叫。 –
你正在使用什麼樣的轉換,以及檢查「TransferRecord記錄是否存在」的代碼在哪裏運行? – ddewaele
代碼在由另一個bean調用的bean中運行。調用bean是無狀態的並且執行很多秒。在bean的操作結束之前,數據不會顯示給其他數據庫用戶。 –