1
這是我的OneToOne映射的SpringBoot Jpa實現。 Hibernate試圖在company_details
表中爲company_id
外鍵插入空值,當我保存時,如下面的代碼CompanyService.createCompany()
所示。 感謝任何幫助。Hibernate嘗試爲OneToOne實體關係外鍵插入null
CREATE TABLE companies (
id BIGSERIAL PRIMARY KEY NOT NULL,
access_token VARCHAR(255) NOT NULL,
access_secret VARCHAR(255) NOT NULL,
token_expires_at TIMESTAMP WITH TIME ZONE NOT NULL
);
CREATE TABLE company_details (
id BIGSERIAL PRIMARY KEY NOT NULL,
company_id BIGSERIAL NOT NULL REFERENCES companies (id),
company_name VARCHAR(50) NOT NULL
);
@Entity
@Table(name = "companies")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false)
private Long id;
@OneToOne(
fetch = FetchType.EAGER,
mappedBy = "company",
cascade = CascadeType.ALL
)
private CompanyDetails details;
...
}
@Entity
@Table(name = "company_details")
public class CompanyDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
@JoinColumn(name = "company_id")
@MapsId
@JsonBackReference // avoid cyclic references
private Company company;
@Size(max = 50)
@NotNull
private String companyName;
}
@Service
public class CompanyService {
@Autowired
private CompanyRepository companyRepository;
@Transactional
public Company createCompany() {
CompanyDetails cd = new CompanyDetails();
cd.setName("cd");
Company c = new Company();
c.setDetails(cd);
this.companyRepository.save(c);
}
}
感謝您的幫助。 – NaveenBabuE
很高興爲你解決 –