【发布时间】:2015-05-07 00:53:51
【问题描述】:
首先,我不知道这是否是解释我的问题的最佳标题,但我们开始吧:我有一个名为Product 的类,它在ProductPriceHistory 上有一个@OneToOne 映射。
@Entity(name = "product")
public class Product {
@Id
@SequenceGenerator(name="seq_product", sequenceName="seq_product", allocationSize=1 )
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_product")
private long id;
@Column(name="description", length=150)
private String description;
@OneToOne
private ProductPriceHistory price;
(...)
public double getPrice() {
double price = 0.0;
ProductPriceHistoryDaoImpl productPriceHistoryDaoImpl = new ProductPriceHistoryDaoImpl();
try {
productPriceHistoryDaoImpl.beginTx();
price = productPriceHistoryDaoImpl.getCurrentPriceByProductId(this.id);
productPriceHistoryDaoImpl.commitTx();
} catch(Exception e) {
(...)
}
return price;
}
}
正如您在我的getPrice() 方法中看到的那样,我正在调用另一个Dao 来检索产品的当前价格。几次都可以,但是在像 10x 一样调用它之后,看起来事务仍然打开,因为我得到了这个异常(我猜它是 PostgreSQL 特有的):ERROR: FATAL: remaining connection slots are reserved for non-replication superuser connections。
我已经尝试过这种方法:实例化ProductPriceHistoryDaoImpl productPriceHistoryDaoImpl,在调用getPrice() 的代码之外打开事务并关闭它,然后通过参数传递它来调用查询,这很完美(插槽没有被重载为在第一种方法中),但我不喜欢这种方法,因为我在.jsp 页面内使用getPrice(),并且在这些情况下我不能通过参数传递ProductPriceHistoryDaoImpl。
添加更多代码只是为了更清晰
public class ProductPriceHistoryDaoImpl extends DefaultDaoImpl<ProductPriceHistory>{
private EntityManager em = HibernateManager.getEntityManager();
public ProductPriceHistory() {
super(ProductPriceHistory.class);
}
public double getCurrentPriceByProductId(long productId) {
(...)
}
}
DefaultDaoImpl.java
public abstract class DefaultDaoImpl<T> {
private EntityManager em;
public void beginTx() {
em = HibernateManager.getEntityManager();
em.getTransaction().begin();
}
public void commitTx() {
em.getTransaction().commit();
em.close();
}
(...)
}
【问题讨论】:
标签: hibernate postgresql transactions