jpanamed-querytoplink

NamedQuery selectively define attributes


I have namedQuery in Entity class defined as

@NamedQuery(name = "Emp.findAll", 
query = " select new test.entity.Emp(o.empNo, o.salary, o.project) from Emp o ") 

Constructor

public Emp(String empNo, String salary, Project project) {
        this.empNo = empNo;
        this.salary=  salary;
        this.project = project;
        }  

and generated SQL is

SELECT t0.emp_no, t0.salary, t1.project_id, t1.project_name, t1.project_desc
FROM EMP t0, PROJECTS t1 WHERE (t1.project_id (+) = t0.project_id)

In namedQuery how do I selectively declare projectId and projectName instead of all attributes from Project class? I wouldn't like to display all attributes of Project class in namedQuery.

How can I achieve this?

Update 1

public Emp(String empNo, String salary, Long projectId, String projectName) {
        Project pr = new Project();
        this.empNo = empNo;
        this.salary=  salary;
        pr.setProjectId = projectId;
        pr.setProjectName = projectName;
        }

Solution

  • Try this (and update the constructor accordingly)

    @NamedQuery(name = "Emp.findAll", 
    query = " select new test.entity.Emp(o.empNo, o.salary, p.projectId, p.projectName) from Emp o inner join o.project p ")
    

    Constructor will be something like this

    public Emp(String empNo, String salary, Long projectId, String projectName) {
        this.empNo = empNo;
        this.salary=  salary;
        Project pr = new Project();
        pr.setProjectId(projectId);
        pr.setProjectName(projectName);
    
        this.project = pr;
    }