有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在JPQL中使用内部联接为3个表选择所有行

我在JPQL中选择3个表中的所有行时遇到问题。我想把它作为Collection<Object>返回

protected Collection<Object> getRecords(){
    emf = Persistence.createEntityManagerFactory("MyPersistenceUnit");
    em = emf.createEntityManager();

    em.getTransaction().begin();

    TypedQuery<Object> query = em.createQuery("SELECT * FROM Vehiclehistory As h INNER JOIN Vehicles As v ON h.vehicleID = v.vehicleID INNER JOIN Clients As c ON h.clientID = c.clientID",Object.class);
    Collection<Object> list = query.getResultList();

    em.getTransaction().commit();

    return list;
}

显示的错误是:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: An exception occurred while creating  a query in EntityManager: 
Exception Description: Syntax error parsing [SELECT * FROM Vehiclehistory As h INNER JOIN Vehicles As v ON h.vehicleID = v.vehicleID INNER JOIN Clients As c ON h.clientID = c.clientID]. 
[138, 138] A select statement must have a FROM clause.
[7, 7] The left expression is missing from the arithmetic expression.
[9, 138] The right expression is not an arithmetic expression.

这是问题吗?我应该使用createQuery还是createNativeQuery?或者我应该只使用Query而不是TypedQuery吗

多谢各位


共 (1) 个答案

  1. # 1 楼答案

    感谢这个链接:INNER JOIN IN JPQL

    比如:

    SELECT v.[vehicleinfo] FROM Vehiclehistory AS h INNER JOIN h.vehicleID AS v ON h.vehicleID = v.vehicleID
    

    h.vehicleID as v

    它只告诉我需要首先引用左表中的外键,并给它一个别名,这样我就可以轻松地调用它,并在上使用它