EJB QL Create new Object In Select Statement : EJB Query Language « JPA « Java Tutorial






File: Main.java

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAService");

  static EntityManager em = emf.createEntityManager();

  public static void main(String[] a) throws Exception {
    em.getTransaction().begin();

    String projectName = "jdk";

    em
        .createQuery(
            "SELECT NEW EmpMenu(e.name, e.department.name) "
                + "FROM Project p JOIN p.students e " + "WHERE p.name = :project "
                + "ORDER BY e.name").setParameter("project", projectName).getResultList();

    em.getTransaction().commit();
    em.close();
    emf.close();

    Helper.checkData();
  }
}
class EmpMenu {
  private String employeeName;
  private String departmentName;

  public EmpMenu(String employeeName, String departmentName) {
      this.employeeName = employeeName;
      this.departmentName = departmentName;
  }

  public String getEmployeeName() { 
      return employeeName;
  }
  
  public String getDepartmentName() {
      return departmentName;
  }
}

File: Department.java

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Department {
    @Id
    private int id;
    private String name;
    @OneToMany(mappedBy="department")
    private Collection<Student> students;

    public Department() {
        students = new ArrayList<Student>();
    }
    
    public int getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    public Collection<Student> getStudents() {
        return students;
    }

    public String toString() {
        return "Department no: " + getId() + 
               ", name: " + getName();
    }
}

File: Project.java

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Project {
    @Id
    protected int id;
    protected String name;
    @ManyToMany(mappedBy="projects")
    private Collection<Student> students;

    public Project() {
        students = new ArrayList<Student>();
    }

    public int getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }
    
    public Collection<Student> getStudents() {
        return students;
    }
    
    public String toString() {
        return "Project id: " + getId() + ", name: " + getName();
    }
}

File: Student.java

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@NamedQueries({
  @NamedQuery(name="findStudentAboveSal",
              query="SELECT e " +
                    "FROM Student e " +
                    "WHERE e.department = :dept AND " +
                    "      e.salary > :sal"),
  @NamedQuery(name="findHighestPaidByDepartment",
              query="SELECT e " +
                    "FROM Student e " +
                    "WHERE e.department = :dept AND " +
                    "      e.salary = (SELECT MAX(e2.salary) " +
                    "                  FROM Student e2 " +
                    "                  WHERE e2.department = :dept)")
})
public class Student {
    @Id
    private int id;
    private String name;
    private long salary;
    @Temporal(TemporalType.DATE)
    private Date startDate;
    
    @ManyToOne
    private Student manager;
    
    @OneToMany(mappedBy="manager")
    private Collection<Student> directs;

    @ManyToOne
    private Department department;
    
    @ManyToMany 
    private Collection<Project> projects;

    public Student() {
        projects = new ArrayList<Project>();
        directs = new ArrayList<Student>();
    }

    public int getId() {
        return id;
    }
    
    public String getName() {
        return name;
    }

    public long getSalary() {
        return salary;
    }

    public Date getStartDate() {
        return startDate;
    }
    
    public Department getDepartment() {
        return department;
    }
    
    public Collection<Student> getDirects() {
        return directs;
    }
    
    public Student getManager() {
        return manager;
    }

    public Collection<Project> getProjects() {
        return projects;
    }
    
    public String toString() {
        return "Student " + getId() + 
               ": name: " + getName() +
               ", salary: " + getSalary() +
               ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName());
    }
}

File: Helper.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Helper {
  public static void checkData() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
    Statement st = conn.createStatement();

    ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
    while (mrs.next()) {
      String tableName = mrs.getString(3);
      System.out.println("\n\n\n\nTable Name: "+ tableName);

      ResultSet rs = st.executeQuery("select * from " + tableName);
      ResultSetMetaData metadata = rs.getMetaData();
      while (rs.next()) {
        System.out.println(" Row:");
        for (int i = 0; i < metadata.getColumnCount(); i++) {
          System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)+ ",  ");
          System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)+ ":  ");
          Object value = rs.getObject(i + 1);
          System.out.println("    Column Value: "+value+"\n");
        }
      }
    }
  }
}

File: persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence" version="1.0">
  <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
      <property name="hibernate.connection.username" value="sa"/>
      <property name="hibernate.connection.password" value=""/>
      <property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
    </properties>
  </persistence-unit>
</persistence>
  Download:  JPA-EJBQLCreatenewObjectInSelectStatement.zip( 5,292 k)








22.25.EJB Query Language
22.25.1.EJB QL Get Two Properties From Entity
22.25.2.EJB QL Get Single result
22.25.3.EJB QL Get Field From Entity
22.25.4.EJB QL Get Entity From Entity
22.25.5.EJB QL Get Distinct Entity
22.25.6.Query an Entity as Query a Table
22.25.7.Return List Of Entities From Query
22.25.8.Query Flush Mode
22.25.9.EJB SQL Count Function
22.25.10.Like statement: Wild Card Escape
22.25.11.Like statement and Wild Card
22.25.12.Where Clause With SubQuery
22.25.13.Use Between To check Salary Range
22.25.14.Two Aggregate Functions
22.25.15.Three Level Field Reference
22.25.16.Using SubQuery in EJB Query Langauge
22.25.17.Size function
22.25.18.Range Check With Comparison Operator
22.25.19.Query Field Of Field
22.25.20.EJB QL Pass Entity As Parameter
22.25.21.Query with Parameters
22.25.22.EJB QL Order By Two Fields
22.25.23.Query One To Many Collection
22.25.24.Order Descending
22.25.25.Use Object Function
22.25.26.Not In function
22.25.27.EJB Query Language: Not Exist
22.25.28.EJB QL Max With Date Type
22.25.29.EJB QL Left Join One To Many Map
22.25.30.EJB QL Join Two Entities
22.25.31.EJB QL Join Three Entities
22.25.32.EJB QL Join One To One Return Two Entities
22.25.33.EJB QL Join One To One
22.25.34.EJB QL Join One To Many Map
22.25.35.EJB QL Join One to Many Left Join Fetch
22.25.36.EJB QL Join Many To Many
22.25.37.EJB QL Join Entity And Its Field
22.25.38.EJB QL is Field empty
22.25.39.EJB QL In With Subquery
22.25.40.EJB QL In Function With One To Many
22.25.41.EJB QL In Function
22.25.42.EJB QL Having Clause
22.25.43.EJB QL Exist And Subquery
22.25.44.EJB QL Create new Object In Select Statement
22.25.45.EJB QL Count Entity
22.25.46.EJB QL Count distinct
22.25.47.EJB QL Concat Function Substring
22.25.48.EJB QL Between With Date Type Value
22.25.49.Aggregate function: AVG