我的实体如下
@Entity
@Table(
name = "t1",
uniqueConstraints = {
@UniqueConstraint(name = "u1", columnNames = {"u1"}),
@UniqueConstraint(name = "u2", columnNames = {"u2_id"}) //This does not enforce uniqueness
}
)
public class t1
{
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String u1; //Uniqueness is enforced here
@OneToOne
@JoinColumn(unique = true) //This does not enforce uniqueness
private U2 u2;
}
@Entity
@Table(
name = "u2",
uniqueConstraints = {
@UniqueConstraint(name = "p1", columnNames = {"p1"})
}
)
public class u2
{
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String p1; //Uniqueness is enforced here
}
通过
创建和更新实体t1 t1_0 = new t1("t1_0");
t1 t1_1 = new t1("t1_1");
u2 u2_0 = new u2("u2_0");
repository.save(t1_0);
repository.save(t1_1);
repository.save(u2_0);
t1_0 = repository.findOne(t1_0.getId());
t1_1 = repository.findOne(t1_1.getId());
t1_0.setu2(u2_0);
t1_1.setu2(u2_0);
事务结束后,t1_0.u2与u2_0相连,t1_1.u2与u2_0相关联。我预计它会抛出唯一性约束违例异常。
不明白出了什么问题。 SO上的其他主题建议@JoinColumn(unique = true)
应该这样做。
修改 这包含在一个事务中
t1_0 = repository.findOne(t1_0.getId());
t1_1 = repository.findOne(t1_1.getId());
t1_0.setu2(u2_0);
t1_1.setu2(u2_0);
EDIT2
由于某些原因,我也无法访问数据库。控制台视图加载但在添加密码后显示用户空白页面(某些网络查询失败)。
但我可以从日志中看到创建外键和唯一约束
Hibernate: alter table driver add constraint UK_ssh305wwvomjtn6opolug33nj unique (cardo_id)
Hibernate: alter table car add constraint FKosnia01vhqwmm888uxrg4o6f6 foreign key (manufacturerdo_id) references manufacturer
Hibernate: alter table driver add constraint FK3yb5ci9sr6ieo6n4wwwef3puv foreign key (cardo_id) references car
添加时
答案 0 :(得分:0)
我的交易无效。由于他们没有看到对方的数据,我错误地在另一个内创建了一个。
答案 1 :(得分:-1)
应使用逗号引入列名称(如果多于一个)。 你的惯例是错误的
免责声明:未在真实数据库中检查
@Table(
name = "t1",
uniqueConstraints = {
@UniqueConstraint(name = "u1", columnNames = {"u1"}),
@UniqueConstraint(name = "u2", columnNames = {"u2", "id"}) // comma
}
)