Question:
I have the following query in the postgres database:
select * from trabalha_projeto tp inner join Empregado e on
e.matricula = tp.empregado
how do I turn it into a JPQL query?
I'm having a hard time returning the values:
- First: not knowing how to formulate the query with jpql
- Second: Due to the fact that it has two java entities, and to list them, it has three tables in the database
My two Employee and Project entities saw the tables:
Project
Employee
Employee_Project (employee_enrolls,projects_code)
Here are my java classes:
Employee Class
@Entity
@SequenceGenerator(name = "empregado_sequence", sequenceName = "empregado_sequence",
allocationSize = 1, initialValue = 1)
public class Empregado implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "empregado_sequence")
private int matricula;
private String nome;
private Double salario;
@OneToMany(cascade = CascadeType.ALL, targetEntity = Projeto.class ,fetch = FetchType.EAGER)
private List<Projeto> projetos;
public Empregado() {
}
Project Class
@Entity
@SequenceGenerator(name = "projeto_sequence" , sequenceName = "projeto_sequence",
allocationSize = 1 , initialValue = 1)
public class Projeto implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE , generator = "projeto_sequence")
private int codigo;
private String nome;
public Projeto() {
}
How to return all employees working on a project using a join?
Answer:
In HQL/JPQL Relational object queries, the query is made based on the Classes and not the database tables, without the names of the Classes/Fields it is difficult to give it to you exactly, but following the convention, your query would look like this:
from Projeto p join p.empregado
If the query does not work, check the name of your Classes and the join field (employee), also add the where clause if you have one.