我有一个问题,我在创建新对象并尝试使用Spring data-jpa使用分离对象保存它。
我的方案是属于特定状态的用户,并且该用户可以更改配置。如果用户尝试更改配置并且配置不存在,则需要使用该状态创建新配置。
但是当我尝试这样做时,我会收到以下错误:
org.hibernate.PersistentObjectException: detached entity passed to persist: com.testproj.tester.pojo.EvState
org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124)
org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:765)
org.hibernate.internal.SessionImpl.persist(SessionImpl.java:758)
org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:398)
org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:162)
org.hibernate.engine.internal.Cascade.cascade(Cascade.java:111)
努力
我在这里创建了所有jparepositories是配置和状态的代码:
@Entity
@Table(name = "ev_layout_configuration")
public class EvConfiguration {
.....
@OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
private EvState evState;
...
}
我也尝试过cascadeType.ALL。
@Entity
@Table(name = "ev_state")
public class EvState {
@Id
@GeneratedValue(generator = "sequence")
@GenericGenerator(name = "sequence", strategy = "sequence", parameters = {
@Parameter(name = "sequence", value = "ev_vahan_sequence") })
@Column(name = "id")
private Long id;
@Column(name = "state_tin_code")
private Integer stateTinCode;
@Column(name = "state_name")
private String stateName;
@Column(name = "state_short_name")
private String stateShortName;
@Column(name = "updated_by")
private String updatedBy;
.....
}
saveConfiguration code
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
EvUser evUser = userRepository.findByEmail(user.getUsername());
evConfiguration = evConfigurationRepository.findByEvState(evUser.getEvState());
System.out.println("============================User from State : " + evUser.getEvState().getStateName()
+ " =============================");
if (evConfiguration == null) {
evConfiguration = new EvConfiguration();
evConfiguration.setState(evUser.getEvState());
evConfiguration = evConfigurationRepository.save(evConfiguration);
}
请朋友帮助我。我正在使用spring data-jpa和hibernate和postgres。