我有3节课。
这3个类表示我的数据库中的表。 UserCars表链接Car和Users表,它的构造方式如下:
--- ---用户
int id
int cars_id
int user_id
-----
我尝试使用Users_car表保存与其用户相关的汽车。
这是我的3个班级:
的车
@Entity
public class Car extends Model{
@Id
@GeneratedValue
public int id;
public String brand;
public String model;
public String fuel;
public double avg_cons; // Average consumption
public double c02_cons;
public double htva_price;
public double leasing_price;
public static Finder<String, Car> find = new Finder<String, Car>(
String.class, Car.class
);
}
用户
@Entity
public class User extends Model{
@Id
@GeneratedValue
public int id;
public String name;
public String username;
public String email;
public String password;
public String phoneNumber;
public Timestamp inscriptionDate;
@Transient
public Timeline timeline;
public User(){}
}
UserCars
@Entity
@Table(name = "user_cars")
public class UserCars extends Model{
@Id
@GeneratedValue
public int id;
@ManyToOne
public int user_id;
@OneToOne
public int car_id;
public UserCars(int userId, int carId){
this.user_id = userId;
this.car_id = carId;
}
public static Finder<String, UserCars> find = new Finder<String, UserCars>(
String.class, UserCars.class
);
}
这就是我保存它的方式:
public static Result saveCar(){
// Retrieve the current username
DynamicForm params = Form.form().bindFromRequest();
String username = params.get("username");
User current = User.find.where().like("username", username).findUnique();
int currentUserId = current.getId();
// Get data from android and save it to DB
Car car = Form.form(Car.class).bindFromRequest().get();
int currentCarId = car.id;
UserCars userCars = new UserCars(currentUserId, currentCarId);
try {
Ebean.save(car);
Ebean.save(userCars);
} catch (OptimisticLockException e) {
e.printStackTrace();
return internalServerError("Car registration failed");
}
return ok();
}
问题是,在int currentCarId = car.id;
行,id 总是 0。
确实只有在我保存汽车时才会增加ID(Ebean.save(car);
)。
如何增加ID,以便正确递增此ID以创建正确的UsersCars实例?
非常感谢!
答案 0 :(得分:2)
您可以在汽车和用户之间创建ManyToMany关系。喜欢
@Entity
public class Car extends Model{
//other fields
@ManyToMany
public List<User> users=new ArrayList<User>();
}
@Entity
public class User extends Model{
//other fields
@ManyToMany
public List<Car> users=new ArrayList<Car>();
}
以上代码会自动创建第三个表格,表示User_Cars(您可以更改名称),其ID分别为Car和User。
同时检查Example