我在spring boot中创建一个项目,通过api调用创建记录。 所以下面有两个表(姓名和电话)是我的域名:
@Entity
@Table(name = "name")
public class Name {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "name", nullable = false)
private String name;
@Column(name = "active", nullable = false)
private boolean active = true;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "name")
@JsonIgnoreProperties("name")
private List<Phone> phones;
}
和
@Entity
@Table(name = "phone")
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "number", nullable = false)
private String number;
@Column(name = "active", nullable = false)
private boolean active = true;
@ManyToOne(targetEntity= Name.class)
@JoinColumn(name="name_id"))
private Name name;
}
创建名称的代码如下:
public Name createNewName(Name createName) {
Name newName = new Name();
newName = NameRepo.save(createName);
return newName;
}
并且存储库是:
@Repository
public interface NameRepository extends PagingAndSortingRepository<Name, Long> {}
所以我的问题是当我使用api发送请求来调用它时,Name不存储Phone值,如果存在则也不链接。
我的要求如下:
{
"name": "testrretf",
"active": true,
"phones":[{
"id":1
}]
}
此请求应将新名称链接到现有的电话ID = 1 并且
{
"name": "testrretf",
"active": true,
"phones":[{
"number":"Test Phone",
"active":true,
}]
}
此请求应创建一个电话并链接到创建的名称。
请帮帮我..
谢谢,
更新#下面是创建表格查询:
CREATE TABLE `name` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `IDX_NAME` (`name `),
KEY `IDX_NAME_ACTIVE` (`active`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
CREATE TABLE `phone` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`name_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_PHONE_ACTIVE` (`active`),
KEY `fk_name_phone` (`name_id`),
CONSTRAINT `fk_name_phone` FOREIGN KEY (`name_id`) REFERENCES `name` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1