org.springframework.dao.invaliddataaccessapiusageexception:传递给persist的分离实体

f87krz0w  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(362)

我有两个模型,一个用于存储用户详细信息,并且使用该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
}

我的spring boot应用程序类中,我尝试将记录插入到两个表中

@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数据库

o2g1uqev

o2g1uqev1#

必须确保两个保存操作都在同一事务中,否则会分离第一个实体,从而导致此异常。
所以只要加上 @Transactional 运行方法:

@Transactional
@Override
public void run(String... args) throws Exception {

相关问题