Answer the question
In order to leave comments, you need to log in
How to add an element with a foreign key to the database (hibernate) without selecting an object for it (by id)?
Let's say there are two Entities linked by a foreign key:
@Entity
@Table(name = "a")
public class AEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false)
private String name;
}
@Entity
@Table(name = "b")
public class BEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "a_id", nullable = false)
private AEntity a;
@Column(name = "name", nullable = false)
private String name;
}
Answer the question
In order to leave comments, you need to log in
I do not know of a "legal" way, and it is unlikely that there is one. the meaning of Jpa is that you work in the object model, and not with sql queries.
you can send a request from the frontend in the form:
{
"name": "some name",
"a": {
"id": 1
}
}
@JsonIgnore
@OneToMany(mappedBy = "a")
private List<BEntity> bs;
@Entity
@Table(name = "b")
public class BEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "a_id", nullable = false)
@JsonIgnore
private AEntity a;
@Transient
private Long aEntityId;
@Column(name = "name", nullable = false)
private String name;
}
// получаешь ответ с фронденда:
BEntity b = getBEntity();
// Создаешь AEntity
AEntity a = new AEntity();
// запихиваешь в нее нужный id из транзаент поля
a.setId(b.getAEntityId());
//засовываешь А в Б
b.setA(a);
// можно сохранять
If you don't have save cascading for BEntity.a, then it will be enough for you to initialize an object of the AEntity class with the specified id, nothing more is required for linking.
As an option, add the aId field to BEntity, and make BEntity.a non-modifiable:
@Column(nullable = false)
private Long aId;
@ManyToOne
@JoinColumn(name = "a_id", nullable = false, insertable = false, updatable = false)
private AEntity a;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question