我在MVC SpringBoot应用程序中遇到了JPA关系的问题。
我正在尝试创建一个应用程序,其中我有许多用户,每个用户都可以拥有多个汽车。用户可以拥有多辆汽车。我在用户和汽车对象之间建立了@OneToOne关系,这就是我所做的:
这是User类:
@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;
}
然后我有端点,但完全有效。添加方法看起来像是应该工作,至少我得到了预期的输出,但是我不知道如何编写它的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();
}
我非常感谢您提供的任何帮助。
非常感谢
答案 0 :(得分:2)
您的映射不正确。汽车&gt;用户是@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();
}
答案 1 :(得分:0)
您可以拥有一个接受用户ID的方法,并返回汽车存储库中的列表,如:
List<Car> findCarByUser(Long userID);
然后你会有
@Override
public List<Car> displayAllCars(Long userId) {
return carRepository.findCarByUser(userId);
}