I have a simple model class like this
@Entity
public class User {
@Id
@GeneratedValue
long id;
@Column(unique = true)
String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am trying to persist instance of User class detached (when the id of the transient object is not null).
I was expecting "detached entity passed to persist" exception, however I am not getting that, for this code
User u = new User();
u.setName("u2");
u.setId(2);
repo.save(u);
Here the id is not null, I should get a detached entity passed to persist exception Can somebody explain why?
Spring data is not the same as JPA but a wrapper or a collection of utilities (or so) to ease the use of JPA related stuff and EntityManager
.
Meaning also that Repository
is not the same as EntityManager
. So how are those two related?
If you take a look at the source code of SimpleJpaRepository
Default implementation of the {@link org.springframework.data.repository.CrudRepository} interface
you will see there:
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
Tracing after some more classes for entityInformation.isNew(entity)
leads to AbstractPersistable
and method:
@Transient
public boolean isNew() {
return null == getId();
}
It will not try to persist entity that has an Id set but merge .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.