我正在尝试使用以下代码运行mysql sql语句;
public void createUpdate(Tsaleline entity) {
//Insert
String sql = "Insert into tSaleLine (CenterId, ProductId, Price, VATRate) "
+ "Select :centerId, :productId, :price, :vatrate "
+ "where (Select count(*) from tSaleLine where CenterId = :centerId and ProductId = :productId)=0; "
//Update
+ "Update tSaleLine "
+ "set CenterId = :centerId, "
+ "ProductId = :productId, "
+ "Price = :price, "
+ "VATRate = :vatrate "
+ "where CenterId = :centerId and ProductId = :productId; ";
Query q = getEntityManager().createNativeQuery(sql);
q.setParameter("centerId", entity.getCenterId())
.setParameter("productId", entity.getProductId())
.setParameter("price", entity.getPrice())
.setParameter("vatrate", entity.getVATRate())
.executeUpdate();
}
}
但它出现了错误:
例外
org.apache.jasper.JasperException:javax.ejb.EJBException:javax.persistence.PersistenceException:org.hibernate.exception.SQLGrammarException:无法执行本机批量操作查询
答案 0 :(得分:0)
只有在记录不存在时才会插入。之后,它将更新价格并为指定的记录进行评估。
public void createUpdate(Tsaleline entity) {
//Insert
String sql = "Insert into tSaleLine (CenterId, ProductId, Price, VATRate) "
+ "Select :centerId, :productId, :price, :vatrate "
+ "where not exists (Select * from tSaleLine where CenterId = :centerId and ProductId = :productId); "
//Update
+ "Update tSaleLine "
+ "set Price = :price, "
+ "VATRate = :vatrate "
+ "where CenterId = :centerId and ProductId = :productId; ";
Query q = getEntityManager().createNativeQuery(sql);
q.setParameter("centerId", entity.getCenterId())
.setParameter("productId", entity.getProductId())
.setParameter("price", entity.getPrice())
.setParameter("vatrate", entity.getVATRate())
.executeUpdate();
}
这不是理想的解决方案,因为您使用的JPA实现应该为实体处理INSERT或UPDATE。
答案 1 :(得分:0)
感谢您对Marcelo的兴趣,我做得很蹩脚。
entity.Tsaleline saleline = sf.findByProductIdCenterId(Integer.parseInt(productIds[i]), Integer.parseInt(centerIds[i]));
if (saleline != null)
{
saleline.setPrice(Float.parseFloat(price[i]));
saleline.setVATRate(Float.parseFloat(vat[i]));
sf.edit(saleline);
}
else
{
saleline = new entity.Tsaleline(Integer.parseInt(productIds[i]), Integer.parseInt(centerIds[i]), Float.parseFloat(price[i]), Float.parseFloat(vat[i]));
sf.create(saleline);
}