gpt4 book ai didi

java - JPA EntityManager创建 native 查询不返回外键数据

转载 作者:行者123 更新时间:2023-12-02 04:14:08 27 4
gpt4 key购买 nike

我有两个实体,TableA 和 TableB,它们之间具有多对多映射。当我尝试使用 createNativeQuery 选择所有 table_b 时,我能够获取所有 table_b 的数据,但无法引用 table_a 的任何数据。

表_a实体

@Entity
@Table(name = "table_a")
public class TableA implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;

@Column(name = "data1")
private String data1;

@Column(name = "data2")
private String data2;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "a_b_mapping",
joinColumns = @JoinColumn(name = "a_id"),
inverseJoinColumns = @JoinColumn(name = "b_id"))
private List<TableB> bItems;

// getters/setters
public List<TableB> getBItems() {
if (bItems == null) { bItems = new ArrayList<>(); }

return bItems;
}

public void setBItems(List<TableB> bItems) {
this.bItems = bItems;
}
}

table_b实体

@Entity
@Table(name = "table_b")
public class TableB implements Serializable {

@Id
@Column(name = "id")
private Integer id;

@ManyToMany(mappedBy = "bItems")
private List<TableA> aItems;

// Getters/Setters

public List<TableA> getAItems() {
if (aItems == null) { aItems = new ArrayList<>(); }

return aItems;
}

public void setAItems(List<TableA> aItems) {
this.aItems = aItems;
}

}

注意:我在插入之前手动为 TableB 设置 id

处理器:

@Component
public class ProcessorDAO {

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

@Transactional
public void process() {

EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction entityTransaction = em.getTransaction();

try {
entityTransaction.begin();

Query q = em.createNativeQuery("SELECT * FROM table_b", TableB.class);
List<TableB> tableBItems = q.getResultList();

for (TableB item : tableBItems) {
// Always 0 here?
item.getAItems().size();
}

entityTransaction.commit();
} catch (RuntimeException e) {
if (entityTransaction.isActive()) {
entityTransaction.rollback();
}
throw e;
} finally {
em.close();
}
}
}

如果我使用 TableB 存储库中的 findAll,我就能够获取 AItems,但我试图让它仅与实体管理器一起使用,不确定有什么区别。

最佳答案

在你的例子中,外键实际上在表A中,只选择表B,不可能获得关联。您需要在 native sql 中联接到表 A。从表B中选择*加入表A......

关于java - JPA EntityManager创建 native 查询不返回外键数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56670753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com