我正在开发一个HRM应用程序,所以我对如何通过JPA管理实体感到困惑。
我恢复的情况是多语言环境中的一组表: -雇员 -departments -languages -departments_languages
关注我的数据库表:
员工实体类:
@Entity
@Table(name="employees")
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="employeed_id", unique=true, nullable=false)
private int employeedId;
@Column(nullable=false, length=255)
private String address;
@Temporal(TemporalType.DATE)
@Column(nullable=false)
private Date birthday;
...
//bi-directional many-to-one association to Department
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="department_id", nullable=false)
private Department department
}
部门实体类
@Entity
@Table(name="departments")
@NamedQuery(name="Department.findAll", query="SELECT d FROM Department d")
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="department_id", unique=true, nullable=false)
private int departmentId;
@Temporal(TemporalType.TIMESTAMP)
@Column(name="date_added", nullable=false)
private Date dateAdded;
@Column(name="location_id", nullable=false)
private int locationId;
@Column(nullable=false)
private byte status;
//bi-directional many-to-one association to DepartmentsLanguage
@OneToMany(mappedBy="department")
private Set<DepartmentsLanguage> departmentsLanguages;
//bi-directional many-to-one association to Employee
@OneToMany(mappedBy="department",fetch=FetchType.LAZY)
private Set<Employee> employees;
...
}
DepartmentLanguage Entity
@Entity
@Table(name="departments_languages")
@NamedQuery(name="DepartmentsLanguage.findAll", query="SELECT d FROM DepartmentsLanguage d")
public class DepartmentsLanguage implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private DepartmentsLanguagePK id;
@Column(length=255)
private String description;
@Column(length=255)
private String name;
//bi-directional many-to-one association to Department
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="department_id", nullable=false, insertable=false, updatable=false)
private Department department;
//bi-directional many-to-one association to Language
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="language_id", nullable=false, insertable=false, updatable=false)
private Language language;
...
}
事实上,我问你是否是正确的方法,我如何执行JPA查询:
SELECT * FROM employees
INNER JOIN departments_languages using(department_id)
WHERE employeed_id = 1 and language_id = 1
从这个查询我需要员工信息,部门名称(假设languageId是1)
从eclipse执行查询JPA控制台返回一个包含所有关系的Employee对象,但两者都是相关的结果
请告诉我这种设计的示例查询
答案 0 :(得分:0)
使用获取连接解决了实现查询,例如:
Query query = entityManager.createQuery("select e from Employee as e "
+ "JOIN FETCH e.department d "
+ "JOIN FETCH d.departmentsLanguages dl "
+ "where e.employeedId = :employeeId "
+ "and dl.language = :languageId");
此外,您可以使用EntiyGraph功能来提高JPA风格的性能;)