【发布时间】: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