【发布时间】:2021-11-17 10:25:34
【问题描述】:
我有这些课程:
公司
@Entity(name = "Compania")
@Table(
name = "compania"
)
public class Compania {
@Id
@SequenceGenerator(
name = "compania_sequence",
sequenceName = "compania_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.AUTO,
generator = "compania_sequence"
)
@Column(
nullable = false
)
private Long id;
@Column(
name = "name",
nullable = false,
unique = true
)
private String name;
@Column(
name = "dominio",
nullable = true
)
private String dominio;
@Column(
name = "altas"
)
private String altas;
@Column(
name = "bajas"
)
private String bajas;
@OneToMany(
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
orphanRemoval = true
)
private List<Office> office;
另一方面,我有这个:
办公室
@Entity(name = "Office")
@Table(name = "office")
public class Office {
@Id
@SequenceGenerator(
name = "office_sequence",
sequenceName = "office_sequence",
allocationSize = 1
)
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "office_sequence"
)
@Column(
nullable = false
)
@JsonIgnore
private Long id;
@Column(
name = "idRef",
nullable = false
)
private int idRef;
@Column(
name = "title",
nullable = false
)
private String title;
@Column(
name = "name"
)
private String name;
@Column(
name = "path"
)
private String path;
@ManyToOne
private Compania compania;
所以我的问题是,当我检查 office 对象时,我使用 GET 方法得到了这个:
{
"idRef": 0,
"title": "titulo1",
"name": "office 1",
"path": "path_office",
"compania": null
}
如您所见,公司显示为空,所以这让我很头疼,因为我无法进行这样的查询,例如,我尝试通过以下方式获取与公司相关的办公室id 和他们的头衔:
@Query("select o from Office o where o.compania.id = :companiaId and lower(o.title) like lower(concat('%', :title, '%') ) ")
List<Office> getChilds(@Param("companiaId") Long companiaId, @Param("title")String title);
我该如何解决这个问题?到目前为止,我已经能够使用 Compania 类作为主要实体,使用 CompaniaService、CompaniaRepository... 等来执行很多请求。
但是,现在我需要专门使用 Office,我无法做到。当然,对于我想做的查询,我可以从公司获取办公室列表,然后对其进行迭代以将它们存储在列表中,然后返回该列表,但我觉得这不是正确的方法.
你能帮帮我吗?非常感谢。
这个问题有什么不同的方法吗?
编辑。为了保存实体,我创建了一个 Compania,我通过 POST 方法将其作为 JSON 传递,然后使用 companiaService.save(compania) 保存它,如下所示:
public void postCompania(Compania compania) {
if (compania.getId() != null) {
if (companiaRepository.existsById(compania.getId())) {
throw new IllegalStateException(
"Compañia con id " + compania.getId() + " ya existe"
);
}
}
companiaRepository.save(compania);
System.out.println(compania);
}
我更改了 Compania 中的 OneToMany 关系,使其看起来像这样:
@OneToMany(
mappedBy = "compania",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
orphanRemoval = true
)
private List<Office> office;
要创建 fk,应用程序执行以下操作:
alter table office
add constraint FKj87ris6ubebpw5t7fkmy5i9bx
foreign key (compania_id)
references compania
【问题讨论】:
-
我不完全理解你的问题,但发现了一个错误的映射:@GeneratedValue( strategy = GenerationType.AUTO, generator = "compania_sequence" ) 应该是 GenerationType.SEQUENCE
标签: java spring-boot api jpa