当前位置: 首页 > 知识库问答 >
问题:

InvalidDataAccessapiUsageException:已分离的实体传递给persist

皇甫文乐
2023-03-14

我有两个模型,一个用于存储用户详细信息,使用该Id,我试图将用户位置保存在另一个表中,该表使用用户的相同Id作为主键。

public class User {
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(unique = true)
    private String username;
    @Column(unique=true)
    private String email;
    private String password;
    private String Role;
    
    @OneToOne(mappedBy = "user")
    private UserLocation location;
    
     //...constructors, getters and setters
 
}
@Entity
public class UserLocation {
   
    @Id
    private Long id;

    @OneToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name="id")
    @MapsId
    private User user;
    
    private Point location;
    //...constructors, getters and setters
}
@SpringBootApplication
public class ContainmentZoneAlertApp implements CommandLineRunner {
    @Autowired
    private UserlocationRepository userLocRepo;
    @Autowired
    private UserRepository userRepo;
    public static void main(String[] args) {
        SpringApplication.run(ContainmentZoneAlertApp.class, args);
                
    }
    @Override
    public void run(String... args) throws Exception {
        
        UserLocation userLocation = new UserLocation();
        Geometry geometry = GeometryUtil.wktToGeometry(String.format("POINT (13.0827 80.2707)"));
        //GeometryUtil is a utility class 

        User user = new User(null,"user 3","user3@gmail.com","hello123","user");
        user = userRepo.save(user);
        userLocation.setUser(user);
        userLocation.setLocation((Point)geometry);
        userLocRepo.save(userLocation);
    }

}

caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.saravanan.models.User

为什么我会出现这个错误?坚持是什么意思?我正在使用MySQL数据库(&I)

共有1个答案

萧晔
2023-03-14

您必须确保两个保存操作都在同一个事务中,否则第一个实体被分离,这将导致此异常

因此只需将@transactional添加到run方法:

@Transactional
@Override
public void run(String... args) throws Exception {
 类似资料: