java Entitymanager 在 2 个不同表中使用内部连接查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14849439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:37:10  来源:igfitidea点击:

Entitymanager query in 2 different tables with inner join

javajpa

提问by galao

my current code:

我目前的代码:

TypedQuery<Account> tp = em.createQuery("SELECT a FROM Account a INNER JOIN User u ON u.account_id = a.id WHERE a.email = :email AND a.pwd = :pwd AND a.role = 'admin'", Account.class);
                tp.setParameter("email", this.username);
                tp.setParameter("pwd", this.password);
                Account result = tp.getSingleResult();

but ill get an java.lang.IllegalArgumentException.

但我会得到一个 java.lang.IllegalArgumentException。

what i need is to display a column in the user table.

我需要的是在用户表中显示一列。

something like String name = Account.getName();but the Account entity doesnt have a getName() only the User entity has.

类似于String name = Account.getName();但 Account 实体没有 getName() 只有 User 实体有。

*update

*更新

this is the error

这是错误

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: Exception Description: Syntax error parsing the query [SELECT a FROM Account a INNER JOIN User u ON u.account_id = a.id WHERE a.email = :email AND a.pwd = :pwd AND a.role = 'admin']. Internal Exception: org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException

java.lang.IllegalArgumentException:在 EntityManager 中创建查询时发生异常:异常描述:语法错误解析查询 [SELECT a FROM Account a INNER JOIN User u ON u.account_id = a.id WHERE a.email = :email AND a.pwd = :pwd AND a.role = 'admin']。内部异常:org.eclipse.persistence.internal.libraries.antlr.runtime.EarlyExitException

回答by Elo

Thisarticle explains you have to JOIN like that : you specifiy the table names separated by a coma, and you move the ONcondition in the WHERE.

这篇文章解释了你必须像这样加入:你指定用逗号分隔的表名,然后ONWHERE.

TypedQuery<Account> tp = em.createQuery("SELECT a FROM Account a, User u   WHERE u.account_id = a.id AND a.email = :email AND a.pwd = :pwd AND a.role = 'admin'", Account.class);
            tp.setParameter("email", this.username);
            tp.setParameter("pwd", this.password);
            Account result = tp.getSingleResult();

回答by SudoRahul

Try this.

试试这个。

result.getUser().getName();

result.getUser().getName();

This, though, is under the assumption, that your Account class has a relationship with the User class.

但是,这是在假设您的 Account 类与 User 类有关系的情况下。

The assumption of this being Hibernate/JPArelationship comes from your previous questionand the use HQLin your code above.

这是Hibernate/JPA关系的假设来自您之前的问题以及上面代码中的 use HQL