Hibernate添加到用户的最简单的方法

Hibernate添加到用户的最简单的方法

本文介绍了使用Spring将JPA / Hibernate添加到用户的最简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Let's say I had this in my UserDAO class:

.ALL,mappedBy =owner,fetch = FetchType.EAGER,orphanRemoval = true)
private Set< Vehicle>车辆=新的HashSet< Vehicle>();

@OneToMany(cascade=CascadeType.ALL, mappedBy="owner", fetch=FetchType.EAGER, orphanRemoval=true)private Set<Vehicle> vehicles = new HashSet<Vehicle>();

这是向用户添加新车辆的推荐方式:

Is this the recommended way to add a new vehicle to a User:

User user = userService.findByLoginName("MartinL");
Vehicle newVehicle = new Vehicle();
newVehicle.set(...) // setters omitted
newVehicle.setOwner(user)  // is this needed in any case?
user.getVehicles().add(newVehicle) // add the new vehicle to the Set in User class
userService.save(user); // persist the modified user object to database

这是最佳实践 或者我想念任何事情?

Is this the best practice or do I miss on anything?

推荐答案

您通常希望管理关系(JPA定义的)依赖关系的双向关联,并在依赖类中。伪代码:

You normally want to manage bidirectional associations from the (JPA defined) dependent side of the relationship, and within the dependent class. Pseudocode:

class User {
    private Set<Vehicle> vehicles;

    public void addVehicle(Vehicle vehicle) {
        if(vehicle == null) return;

        vehicle.setOwner(this);
        vehicles.add(vehicle);
    }

    public void removeVehicle(Vehicle vehicle) {
        if(vehicle == null) return;

        if(vehicles.remove(vehicle)) {
            vehicle.setOwner(null);
        }
    }
}

管理关系之外的关系实体导致错误和重复的代码。

Managing the relationship outside of the entities leads to bugs and duplicated code.

这篇关于使用Spring将JPA / Hibernate添加到用户的最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 08:22