JPA EntityManager创建本机查询不返回外键数据

时间:2019-06-19 15:01:26

标签: java spring-boot jpa

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

table_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,但是我试图让它仅与实体管理器一起使用,不确定有什么区别。

1 个答案:

答案 0 :(得分:0)

在您的情况下,外键实际上在表A中,仅选择表B,就无法获得关联。您需要加入本机sql中的表A。 从表B中选择* 加入tableA .....