我有一个在EJB bean中保存新对象的方法。调用此方法时没有错误,但数据库中没有任何更改。我不明白为什么。
以下是代码:
@Stateless(name = "Ar", mappedName = "ManagementBean")
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
...
@Override
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp,
boolean toBeAnalysed, String phoneNumber) {
// Get phone number, create if it dosn't exist
PhoneNumber pn = getOrCreatePhoneNumberPrivate(phoneNumber);
// Create rawSMS
RawSms rawSms = new RawSms(raw, requestUid, text, service, correctlyAnalysed, receivedTimestamp, toBeAnalysed, pn);
// Store and return result
em.persist(rawSms);
int result = rawSms.getId();
em.flush();
em.clear();
return result;
}
...
来电者:
@PersistenceContext private EntityManager em;
...
int rawSmsIs = bean.storeRawSms(raw, requestUid, message, service, false, new Date(), true, sender);
你有什么想法吗?
答案 0 :(得分:0)
我看到你在客户端注入了对EntityManager的引用(不知道为什么),但是我没有在会话bean中看到它(可能只是因为你没有在你的消息中包含该行)。是否有可能忘记在无状态会话bean中使用注释@PersistenceContext?
另外,请注意:根据您使用的JPA实现和ID的生成策略,您应该在调用getId()之前调用flush() 。实际上,如果您让DB生成您的ID,那么您需要flush()才能在方法返回值之前实现此目的。
答案 1 :(得分:0)
谢谢,建议的解决方案有效!
我使用像这样的容器管理的事务:
@Stateless(name = "Ar", mappedName = "ManagementBean")
@TransactionManagement(TransactionManagementType.CONTAINER)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
....
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public int storeRawSms(String raw, String requestUid, String text, String service, boolean correctlyAnalysed, Date receivedTimestamp, boolean toBeAnalysed, String phoneNumber) {
....
再次感谢!
答案 2 :(得分:-1)
您的交易似乎从未提交,因此请尝试更改交易管理:
@Stateless(name = "Ar", mappedName = "ManagementBean")
@TransactionManagement(TransactionManagementType.BEAN)
public class ManagementBean implements IManagementBeanLocal, IManagementBeanRemote {
@Resource
private UserTransaction utx;
@Override
public int storeRawSms(..) {
try {
utx.begin();
..
em.persist(rawSms);
int result = rawSms.getId();
utx.commit();
}
catch(Exception ex) {
//EXCEPTION HANDLING
utx.rollback();
}
}
}