简体   繁体   English

在mysql休眠中保存子实体时忽略唯一约束

[英]Unique constraint Ignored while saving child entity in mysql hibernate

I have two tables. 我有两张桌子。 Consider them as below. 如下考虑它们。 Person has OneToMany relationship with Phone. 人与手机有OneToMany关系。

create table Person(
  id varchar,
  name varchar
);

create table Phone(
  id varchar,
  name varchar,
  person_id varchar,
  UNIQUE KEY `unq` (`name`)
  FOREIGN KEY (person_id) REFERENCES Person(id)
);

Now Java Code looks as below. 现在,Java代码如下所示。

Person person = new Person();
Phone phone = new Phone();
phone.setPerson(person);
phoneRepository.save(phone);

Query ignores unique constraint on the child table while insertion. 查询在插入时忽略子表上的唯一约束。 It is saving multiple duplicate entries 正在保存多个重复的条目

What seems to be causing issue? 似乎是什么引起了问题? Is it expected behavior? 这是预期的行为吗?

You have to store existing Person entity 您必须存储现有的Person实体

Instead to instantiate a new entity 而是实例化一个新实体

Person person = new Person();

try to read existing entity 尝试阅读现有实体

Person existingPerson = personRepository.findOneByName(name);

and set the existing entity to your phone 并将现有实体设置为您的手机

phoneRepository.save(existingPerson)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM