2017-03-29 68 views
0

我有Employee類。 A Worker類延伸Employee,而Leader類延伸WorkerJPQL返回java.langObject,期望類型的instad

每個Leader有一個列表public List workersResponsibleFor = new ArrayList<>();。哪個是Join表,用於說明Leader是否對一個或多個Workers負責。

@Entity 
@Inheritance 
@DiscriminatorColumn(name="EMP_TYPE") 
@Table(name="EMPLOYEES") 
public abstract class Employee implements Printable, Serializable { 

    @Id 
    @GeneratedValue 
    @Column(name = "employee_id", unique = true) 
    private int id; 

    @Column(name = "position") 
    @Enumerated(EnumType.STRING) 
    private Position position; 

    @Column(name = "name") 
    private String name; 

    @Column(name = "salary") 
    private Double salary; 

    @Transient 
    public List<Project> projectsWorkingOn = new ArrayList<>(); 

    public Employee() { 
    } 
} 

Worker

@Entity 
public class Worker extends Employee { 

    @Id 
    @GeneratedValue 
    @Column(name = "worker_id", unique = true) 
    private int id; 

    public Worker() { 
    } 
} 

Leader

@Entity 
public abstract class Leader extends Worker { 

    public Leader() { 
    } 

    public Leader(Position position, String name, Double salary) { 
     super(position, name, salary); 
    } 

    @OneToMany 
    @JoinTable(name="WORKERS_RESPONSIBLE_FOR", 
      joinColumns = {@JoinColumn(name="RES_ID")}, 
    inverseJoinColumns = {@JoinColumn(name="FOR_ID")}) 
    public List<Worker> workersResponsibleFor = new ArrayList<>(); 
} 

的問題是,每次我試圖讓一個工人回用下面的方法時間:

private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("manager1"); 
private static final EntityManager entityManager = entityManagerFactory.createEntityManager(); 

public Worker exampleQuery() { 
     Worker w; 
     try { 
      Query query = entityManager.createQuery("select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE e1.name LIKE 'James%'"); 
      w = (Worker) query.getSingleResult(); 
     } finally { 
      entityManager.close(); 
      entityManagerFactory.close(); 
     } 
     System.out.println(w.getName()); 
     return w; 
    } 

錯誤:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.company.employees.Worker

我得到了java.lang.Object回來,insted的一個Worker的。但是我所有的其他方法都可以返回Workers,所以可能是我正在使用的查詢的問題?由於

+0

當他們回答您的問題時,請隨時接受答案。如果他們不那麼善意地說,爲什麼不! –

回答

0

select e1, e2 from Employee e1 join e1.workersResponsibleFor e2 WHERE ... 

JPQL總是返回Object[]類型的行(和消息告訴你正是這樣),因爲這是JPA規範定義了它做。如果您查看元素0,它將是e1的類型,元素1將是e2的類型。建議您查看JPA規範或您使用的任何實現的文檔。

如果您選擇的只是候選別名,那麼您會得到一行類型的e1。同樣,在JPA規範中定義!