0
我有兩個表休眠 - 以一對一的關係
用戶
CREATE TABLE "user"
(
id INTEGER PRIMARY KEY NOT NULL,
phone TEXT,
position_id BIGINT,
CONSTRAINT user_position_id_fk FOREIGN KEY (position_id) REFERENCES position (id)
);
CREATE UNIQUE INDEX user_id_uindex ON "user" (id);
位置
CREATE TABLE position
(
id INTEGER PRIMARY KEY NOT NULL,
latitude DOUBLE PRECISION,
longitude DOUBLE PRECISION,
bearing DOUBLE PRECISION,
accuracy DOUBLE PRECISION,
speed DOUBLE PRECISION,
user_id BIGINT,
CONSTRAINT position_user_id_fk FOREIGN KEY (user_id) REFERENCES "user" (id)
);
CREATE UNIQUE INDEX position_id_uindex ON position (id);
他們被標註這樣的映射:
@Entity
@Table(name = "user")
public class User {
public static final String ID = "id";
public static final String PHONE = "phone";
public User() {
position = new Position();
}
@Id
@Column(name = ID, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = PHONE)
private String phone;
@OneToOne(mappedBy = "user")
@Cascade(CascadeType.ALL)
@JoinColumn(name = "id", referencedColumnName = "position_id")
private Position position;
}
@Entity
@Table(name = "position")
public class Position {
public static final String ID = "id";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String BEARING = "bearing";
public static final String ACCURACY = "accuracy";
public static final String SPEED = "speed";
public static final String USER_ID = "user_id";
@Column(name = ID, unique = true)
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = {@org.hibernate.annotations.Parameter(name = "property", value = "user")})
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = LATITUDE)
private double latitude;
@Column(name = LONGITUDE)
private double longitude;
@Column(name = BEARING)
private double bearing;
@Column(name = ACCURACY)
private double accuracy;
@Column(name = SPEED)
private double speed;
@OneToOne
@PrimaryKeyJoinColumn
@Cascade(CascadeType.ALL)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
我將新對象保存到數據庫中。除了一件事,一切都是正確的。字段user_id
和position_id
爲空。有沒有解決方案可以幫助我做到這一點?
我不知道,我瞭解你。你的意思是這樣的嗎?: @OneToOne(mappedBy =「我不知道應該使用哪個字段」) @PrimaryKeyJoinColumn @Cascade(CascadeType.ALL) private User user; –