I am having two Entity classes, Company
and CompanyTypeAutomobile
.
These two have One-To-One
relationships.
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
@Column(name = "company_id", unique = true, nullable = false)
private Integer companyId;
@Column(name = "name", length = 255, updatable = false)
@NotEmpty
private String name;
private CompanyType companyType;
//other fields
}
public class CompanyTypeAutomobile {
@Id
private Integer id;
@JsonIgnore
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "company_id")
private Company company;
}
Company
contains the basic details of a company, and the other fields would be contained in its child entity(based on the type of Company) Now, when If Company
is created, should I create the CompanyTypeAutomobile
also in the same process?
I am having a requirement where I am in such a situation. If for some company, it has only basic details in Company
and other details were not created and I want GET the complete details of the company then the persistence layer would return me EntityNotFoundException
for CompanyTypeAutomobile
.
So I just want to create the child entity, only with the id
field. Is it a good practice?
Now, when If Company is created, should I create the
CompanyTypeAutomobile
also in the same process?
It depends on whether the child entity is mandatory or not.
When you load the child entity using the Company
identifier:
CompanyTypeAutomobile details = entityManager.find(CompanyTypeAutomobile.class, company.getId());
you will get null
if there is no CompanyTypeAutomobile
in the DB, not an EntityNotFoundException
.
So I just want to create the child entity, only with the id field. Is it a good practice?
No, it's not. That would be a hack.
If you get an EntityNotFoundException
, it means you mapped the child association in the parent entity, which is a mistake .
In that case, remove the CompanyTypeAutomobile
association in the parent Company
entity as it will behave according to the EAGER fetching strategy and lead to N+1 query issues .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.