【问题标题】:MVC SpringBoot and JPA RelationshipMVC Spring Boot 与 JPA 的关系
【发布时间】:2017-01-09 16:03:27
【问题描述】:

我对 MVC SpringBoot 应用程序中的 JPA 关系有疑问。

我正在尝试创建一个应用程序,其中有多个用户,每个用户都可以拥有许多汽车。一个用户可以拥有多辆汽车。我已经在用户和汽车对象之间建立了@OneToOne 关系,这就是我所做的:

这里是用户类:

@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "username", nullable = false)
    private String username;

    @Column(name = "password", length = 500, nullable = false)
    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Car> cars;

}

那么这里是 Car 类:

@Entity
@Table(name = "car")
public class Car implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(length = 11)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "make", nullable = false)
    private String make;

    @Column(name = "model", nullable = false)
    private String model;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "id")
    private User user;

}

然后,这里是实际的服务实现

@Component
@Transactional(readOnly = true)
public class CarServiceImpl implements CarService {

@Inject
private CarRepository carRepository;

@Inject
private UserRepository userRepository;

@Override
@Transactional(readOnly = false)
public Car addCar(Long userId, Car car) {
    User user = userRepository.findOne(userId);      
    user.getGpsLocationModels().add(car);

    car.setUser(user);
    carRepository.save(car);

    return car;
}

然后我有端点,但它完全有效。 add 方法看起来像预期的那样工作,至少我得到了预期的输出,但是 find 方法我不知道如何编写它,也无法弄清楚如何根据用户检索汽车,我知道如何通过 ID 获取它们,但不是针对每个用户单独获取。

这是我的尝试:

@Override
public Car findCar(Long userId, Long carId) {

    //get the current user (that comes as JSON Request Param)
    User user = userRepository.findOne(userId);

    //get the car based on its ID, here's the problem, I want the car based on its ID AND its user, I can't display cars which aren't for that particular user
    Car car = carRepository.findOne(carId);

    return car;
}

这是获取特定用户的所有汽车的方法:

@Override
public List<Car> displayAllCars(Long userId) {
    return userRepository.findOne(userId).getCars();
}

如果您能提供任何建议,我将不胜感激。

非常感谢

【问题讨论】:

    标签: java hibernate jpa spring-boot


    【解决方案1】:

    您的映射不正确。汽车 > 用户是 @ManyToOne。如果您还进行此双向操作,您还可以通过用户检索汽车:

    @Entity
    @Table(name = "user")
    public class User implements Serializable {
    
        @OneToMany(mappedBy ="user",cascade = CascadeType.ALL)
        private Set<Car> cars;
    
        public Set<Car> getCars(){
            return cars;
        }
    
        public void addCar(Car car){
            cars.add(car);
            car.setUser(this);
        }
    }
    
    @Entity
    @Table(name = "car")
    public class Car implements Serializable {
    
        @ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinColumn(name="user_id")
        private User user;
    }
    
    @Override
    public Set<Car> findCars(Long userId) {
        return userRepository.findOne(userId).getCars();
    }
    

    【讨论】:

    • 嗨艾伦,非常感谢您的帮助。请查看上面的代码,因为我已经对其进行了编辑。我现在遇到了一个例外。此外,findCars 方法用于获取所有汽车,但是,基于汽车的 ID 或品牌或型号(无论哪种方式),我只需要该特定用户的一辆特定汽车。此外,我还没有建立@ManytoOne 的关系,因为我认为我进行的每个 HTTP 调用都会有一辆车,而不是同一呼叫中的多辆车,但是,代码已按照建议进行了修改。太感谢了。非常感谢:)
    • Sotry,但您的问题已得到解答,现在过于宽泛。
    • 好吧,完全不用担心。至少,您能从上面的代码中告诉我这次映射是否看起来不错吗?非常感谢:)
    【解决方案2】:

    您可以有一个接受用户 ID 并返回汽车存储库中的列表的方法,例如:

    List<Car> findCarByUser(Long userID);
    

    然后你就会有

    @Override
    public List<Car> displayAllCars(Long userId) {
    return carRepository.findCarByUser(userId);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-30
      • 2016-02-02
      • 1970-01-01
      • 2017-05-09
      • 2021-06-15
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多