JPA Tutorial - JPA TypedQuery Example








The following code creates a typed query. The TypedQuery can have generic parameter.

TypedQuery<Professor> query = em.createQuery("SELECT e FROM Employee e",
        Professor.class);

Example

The following code is from Professor.java.

package com.java2s.common;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity 
@Table(name="EMP")
public class Professor  {
    @Id private int id;
    private String name;
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return "Professor id: " + getId() + " name: " + getName();
    }
}

The following code is from PersonDaoImpl.java.

package com.java2s.common;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PersonDaoImpl {
  public void test() {

    Professor emp = new Professor();

    emp.setId(1);
    emp.setName("name");
    em.persist(emp);

    TypedQuery<Professor> query = em.createQuery("SELECT e FROM Employee e",
        Professor.class);
    List<Professor> emps = query.getResultList();

  }

  @PersistenceContext
  private EntityManager em;
}


Download TypedQuery.zip