java – Hibernate merge正在生成新行而不是更新
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Hibernate merge正在生成新行而不是更新,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6346字,纯文字阅读大概需要10分钟。
内容图文
我正在使用Hibernate-EntityManager版本4.3.5.我有多个表使用带有生成值的id.
插入等工作正常,但是当我尝试合并时,Hibernate不会更新旧行并创建新行.
内容相同,但id正在递增.
合并前:
合并后:
我尝试使用自定义Id生成器来检查Id是否已存在.有了这个新策略,我得到以下错误:
Caused by: java.sql.SQLException: Field 'product_id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
编辑:
我发现@GeneratedValues不会在局部变量中设置id.这意味着您可以在合并时覆盖现有的那些.虽然,这并没有解决我的问题.
这是我正在使用的代码:
@Entity(name = "calculation_storage")
@Proxy(lazy = false)
public class CalculationStorage {
@Id
private Date created;
@OneToMany(mappedBy = "storage", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Product> products;
public CalculationStorage(Date created) {
this.created = created;
this.products = new LinkedList<Product>() {
@Override
public boolean add(Product product) {
product.setStorage(CalculationStorage.this);
return super.add(product);
}
};
}
public CalculationStorage(Date created, List<Product> products) {
this.created = created;
this.products = products;
}
public CalculationStorage() {
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
/**
* Durch das aufrufen get add Methode wird der benoetigte Fremdschluesseleintrag gesetzt
*
* @return Alle Produkte die registriert sind
*/
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> entities) {
this.products = entities;
}
PRODUKT:
@Entity(name = "product")
public class Product implements Serializable {
@Id
@Column(name = "product_id")
//@GeneratedValue
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="IdOrGenerated")
@GenericGenerator(name="IdOrGenerated",
strategy="at.iktopia.firmenverwaltung.abendabrechnung.control.hibernate.ProductIdGenerator"
)
private int id;
private double costs;
private String name;
private ProductType type;
@OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<CalculatorEntity> entities;
@ManyToOne
@JoinColumn(name = "product_fk", nullable = false)
private CalculationStorage storage;
public Product(String name, ProductType type, double costs) {
this.name = name;
this.type = type;
this.costs = costs;
this.entities = new LinkedList<>();
}
/**
* JPA - Konstruktor
*/
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
public List<CalculatorEntity> getEntities() {
return entities;
}
public void setEntities(List<CalculatorEntity> entities) {
this.entities = entities;
}
public double getCosts() {
return costs;
}
public void setCosts(double costs) {
this.costs = costs;
}
public CalculationStorage getStorage() {
return storage;
}
public void setStorage(CalculationStorage calculationStorage) {
this.storage = calculationStorage;
}
}
发电机:
public class ProductIdGenerator extends IdentityGenerator {
@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
if (obj == null) throw new HibernateException(new NullPointerException());
if ((((Product) obj).getId()) == 0) return super.generate(session, obj);
else return ((Product) obj).getId();
}
}
调用以合并对象的更新方法:
public class CalculationManager implements Manager<CalculationStorage, Date, CalculationStorageList> {
/**
* @see Manager#save(Object)
*/
@Override
public void save(CalculationStorage calculationStorage) {
Validate.notNull(calculationStorage);
EntityManager em = PersistenceManager.getInstance().getEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
em.persist(calculationStorage);
transaction.commit();
} catch (Exception e) {
ErrorHandler.handleException(e, JPA_PERSIST_ERROR_MESSAGE);
if (transaction.isActive())
transaction.rollback();
}
em.close();
}
/**
* @see Manager#update(Object)
*/
@Override
public void update(CalculationStorage calculations) {
Validate.notNull(calculations);
EntityManager em = PersistenceManager.getInstance().getEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
CalculationStorage c = em.getReference(CalculationStorage.class, calculations.getCreated());
c.setProducts(calculations.getProducts());
em.merge(c);
transaction.commit();
} catch (EntityNotFoundException e) {
if (transaction.isActive())
transaction.rollback();
save(calculations);
} catch (Exception e) {
ErrorHandler.handleException(e, JPA_PERSIST_ERROR_MESSAGE);
if (transaction.isActive())
transaction.rollback();
}
em.close();
}
/**
* @see Manager#getAll()
*/
@Override
public CalculationStorageList getAll() {
EntityManager em = PersistenceManager.getInstance().getEntityManager();
List<CalculationStorage> calculations;
try {
calculations = em.createQuery("SELECT c FROM calculation_storage c").getResultList();
} catch (Exception e) {
ErrorHandler.handleException(e, JPA_LOAD_ERROR_MESSAGE);
return null;
}
em.close();
return new CalculationStorageList(calculations);
}
/**
* @see Manager#remove(Object)
*/
@Override
public void remove(Date primaryKey) {
Validate.notNull(primaryKey);
EntityManager em = PersistenceManager.getInstance().getEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
try {
em.remove(em.getReference(CalculationStorage.class, primaryKey));
transaction.commit();
} catch (Exception e) {
ErrorHandler.handleException(e, JPA_PERSIST_ERROR_MESSAGE);
if (transaction.isActive())
transaction.rollback();
}
em.close();
}
/**
* @see Manager#get(Object)
*/
@Override
public CalculationStorage get(Date primaryKey) {
Validate.notNull(primaryKey);
EntityManager em = PersistenceManager.getInstance().getEntityManager();
try {
CalculationStorage storage = em.getReference(CalculationStorage.class, primaryKey);
em.close();
return storage;
} catch (Exception e) {
ErrorHandler.handleException(e, JPA_LOAD_ERROR_MESSAGE);
return null;
}
}
}
我无能为力导致这个问题.
解决方法:
试着看看:http://www.programmingforfuture.com/2011/02/hibernate-merge-may-insert-new-record.html
它可以帮助你.
内容总结
以上是互联网集市为您收集整理的java – Hibernate merge正在生成新行而不是更新全部内容,希望文章能够帮你解决java – Hibernate merge正在生成新行而不是更新所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。