我有Employee
類。 A Worker
類延伸Employee
,而Leader
類延伸Worker
。JPQL返回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,所以可能是我正在使用的查詢的問題?由於
當他們回答您的問題時,請隨時接受答案。如果他們不那麼善意地說,爲什麼不! –