【发布时间】:2011-07-07 05:36:57
【问题描述】:
以下代码无法可靠地创建新记录。
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 记录”的代码在哪里运行?
-
代码在一个 bean 中运行,该 bean 被另一个 bean 调用。调用 bean 是无状态的,并且会执行许多秒。在 bean 的操作结束之前,数据不会显示给其他数据库用户。