English 中文(简体)
Hibernate saveOrUpdate fails when I execute it on empty table
原标题:

I m try to insert or update db record with following code:

Category category = new Category(); 
category.setName( catName );
category.setId(1L);
categoryDao.saveOrUpdate(category);

When there is a category with id=1 already in database everything works. But if there is no record with id=1 I got following exception:

org.hibernate.StaleStateException:
Batch update returned unexpected row count from update [0]; actual row count: 0; 
expected: 1:

Here is my Category class setters, getters and constructors ommited for clarity:

@Entity
public class Category {    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToOne
    private Category parent;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    private List<Category> categories = new ArrayList<Category>();
}

In the console I see this hibernate query:

update
    Category
set
    name=?,
    parent_id=?
where
    id=?

So looks like hibernates tryis to update record instead of inserting new. What am I doing wrong here?

最佳回答

This is by design.

Hibernate only decides based on the id if it should perform an update or an insert. If it would consider what s already there in the database, it would have to perform an additional query, but it doesn t do this.

Ids are normally managed by Hibernate, unless you map it as generator="assigned" (don t know how this looks using annotations). So you shouldn t just assign a value to it.

In this case, the Id is even given by the database. So if your application would generate Ids at the same time, it would result in duplicated Ids. (And most database do not allow inserting values to auto columns, so it would technically be impossible to store your id).

If you want to generate your own Ids, use generator="assigned", and store it using merge. This will do what you expect: it searches the record in the database, when it exists it will update it, when not it will insert it.

问题回答

try to use save method alone if the rowcount of the table is 0 else use saveorupdate method.





相关问题
Multiple Hibernate instances using C3P0

I am facing a weird problem and it seems to be c3p0 related. I am starting two instances of an app in the same java vm which interact with each other. After some operations "APPARENT DEADLOCK" ...

Hibernate vs Ibatis caching

We can speed up a hibernate app easyly with 2nd level cache using infinispan or ehcache/terracotta,... but ibatis only have a simple interface to implement for caching. And hibernate knows more ...

Using annotations to implement a static join in hibernate

I m relatively new to hibernate and was wondering if someone could help me out. While I have no issues implementing a normal join on multiple columns in hibernate using the @JoinColumns tag, I m ...

Hibernate query with fetch question

I have a 2 entities in a One-To-Many relationship: OfficeView.java: public class OfficeView implements java.io.Serializable { private Integer officeId; private String addr1; private ...

hibernate interceptors : afterTransactionCompletion

I wrote a Hibernate interceptor : public class MyInterceptor extends EmptyInterceptor { private boolean isCanal=false; public boolean onSave(Object entity, Serializable arg1, Object[] arg2, String[]...

How to prevent JPA from rolling back transaction?

Methods invoked: 1. Struts Action 2. Service class method (annotated by @Transactional) 3. Xfire webservice call Everything including struts (DelegatingActionProxy) and transactions is configured ...

Hibernate/GORM: collection was not processed by flush()

I have an integration test in my Grails application that fails when I try to save an entity of type Member invitingMember.save(flush: true) This raises the following exception org.hibernate....

Hibernate Criteria API equivalent for "elements()"

Is it possible to implement the following query using Criteria API? select order from ORDER as order,ITEM as item where item.itemID like ITM_01 and item in elements(order.items)

热门标签