Hibernte Error => EntityExistsException: A different object with the same identifier value was already associated with the session

huangapple go评论83阅读模式
英文:

Hibernte Error => EntityExistsException: A different object with the same identifier value was already associated with the session

问题

我试图从Spring Boot API向我的数据库中插入一个新对象,但是当我调用我的PostMapping时出现错误。

控制器:

@PostMapping("/users/{userId}/vehicles")
public ResponseEntity<String> insertVehicle(@PathVariable Integer userId, @RequestBody Vehicle body) {
    User user = UserRepository.getOne(userId);
    VehicleRepository.save(new Vehicle(VehicleRepository.findAll().size() + 1, body.getBrand(), body.getModel(), body.getRegistration(),
            body.getManufacturingDate(), body.getMileage(), user, body.getComponents()));
    return new ResponseEntity<>("Hello", HttpStatus.OK);
}

Vehicle类:

public class Vehicle {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id = null;

    @Column(name = "brand")
    private String brand = null;

    @Column(name = "model")
    private String model = null;

    @Column(name = "registration")
    private String registration = null;

    @Column(name = "manufacturingDate")
    private String manufacturingDate = null;

    @Column(name = "mileage")
    private String mileage = null;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "userId")
    private User user = null;

    @Transient
    private List<Component> components = null;
}

感谢帮助,祝您有美好的一天。

英文:

I try to insert a new object in my Databse from Spring Boot API, but I have an error when I call my PostMapping

Controller

    @PostMapping(&quot;/users/{userId}/vehicules&quot;)
    public ResponseEntity&lt;String&gt; insertVehicule(@PathVariable Integer userId, @RequestBody Vehicule body) {
        Utilisateur utilisateur = UserRepository.getOne(userId);
        VehiculeRepository.save(new Vehicule(VehiculeRepository.findAll().size()+1,body.getMarque(),body.getModele(),body.getImmatriculation(),
                body.getMiseEnCirculation(),body.getNombreKilometre(),utilisateur,body.getComposants()));
        return new ResponseEntity(&quot;Hello&quot;,HttpStatus.OK);
    }

Class Vehicule

public class Vehicule   {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id = null;

    @Column(name=&quot;marque&quot;)
    private String marque = null;

    @Column(name=&quot;modele&quot;)
    private String modele = null;

    @Column(name=&quot;immatriculation&quot;)
    private String immatriculation = null;

    @Column(name=&quot;miseEnCirculation&quot;)
    private String miseEnCirculation = null;

    @Column(name=&quot;nombreKilometre&quot;)
    private String nombreKilometre = null;
    
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = &quot;userId&quot;)
    private Utilisateur user = null;

    @Transient
    private List&lt;Composant&gt; composants = null;
}

Thanks for help
Have a good day

答案1

得分: 0

如果您在控制器内部设置了id,JPA会尝试更新它,而不是保存实体,然后会出现异常,因为实体并不存在。在创建时,JPA会生成id。

@PostMapping("/users/{userId}/vehicles")
public ResponseEntity<String> insertVehicle(@PathVariable Integer userId, @RequestBody Vehicle body) {
    User user = UserRepository.getOne(userId);
    VehicleRepository.save(new Vehicle(null, body.getBrand(), body.getModel(), body.getRegistration(),
            body.getManufacturingDate(), body.getMileage(), user, body.getComponents()));
    return new ResponseEntity("Hello", HttpStatus.OK);
}
英文:

If you set the id inside the controller, JPA will try to update it instead of save the entity, then you get the exception as it doesnt exists. JPA will generate the id in case of creation.

@PostMapping(&quot;/users/{userId}/vehicules&quot;)
public ResponseEntity&lt;String&gt; insertVehicule(@PathVariable Integer userId, @RequestBody Vehicule body) {
    Utilisateur utilisateur = UserRepository.getOne(userId);
    VehiculeRepository.save(new Vehicule(null,body.getMarque(),body.getModele(),body.getImmatriculation(),
            body.getMiseEnCirculation(),body.getNombreKilometre(),utilisateur,body.getComposants()));
    return new ResponseEntity(&quot;Hello&quot;,HttpStatus.OK);
}

huangapple
  • 本文由 发表于 2020年9月25日 15:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64060034.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定