我已经使用JPA注释在部门和雇员之间创建了一对多关系。实体是:
Department(Parent)
String Id
String Name
List Employee(@OneToMany)
Employee(Child)
Key key
String firstName
String lastName
String Address
Department dept(@ManyToOne)
输入员工的名字时,我想显示该员工的详细信息(姓氏和地址),以及他所属的部门。我没有找到任何从子实体获取父信息的解决方案。有什么方法可以从其子实体获取有关父实体的信息吗?
我认为一种可能的解决方案是从child获取父ID,在另一个查询中获取Parent Detail。但我想在单个查询中提供有关员工的所有信息。这可能吗?
这是我的代码。
Department Entity:
@Entity
public class Department {
@Id
private String id;
private String description;
@OneToMany(mappedBy = "department", fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<Employee> employee = new ArrayList<Employee>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Employee> getEmployee () {
return employee ;
}
public void setEmployee (List<Employee > employee) {
this.employee = employee ;
}
}
Employee Entity:
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String firstName;
private String lastName;
private String Address;
private String parent_Id;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Department department;
public Key getKey() {
return key;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return Address;
}
public void setAddress(String Address) {
this.Address = Address;
}
}
Android代码在后台插入实体
Departmentendpoint.Builder builder1 = new Departmentendpoint.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);
Departmentendpoint dptendpoint = CloudEndpointUtils.updateBuilder(builder1).build();
Department dpt = new Department();
dpt.setDescription("Water Service");
List<Employee> m = new ArrayList<Employee>();
Employee mgr2= new Employee();
mgr2.setFirstName("Avinash"+i);
mgr2.setLastName("Patel"+i);
mgr2.setAddress("Vadodara");
m.add(mgr2);
dpt.setEmployee(m);
try {
dptendpoint.insertDepartment(dpt).execute();
} catch (IOException e) {
e.printStackTrace();
}
您可以从子实体的键获取父ID,但必须从数据存储区获取父实体。
您可以在每个员工实体中存储一个部门名称,这将节省一次get操作,但会浪费额外的数据和更复杂的代码(您必须考虑诸如部门名称更改之类的情况)。
更好的解决方案是将部门实体保留在内存缓存中。这样,您可以保存到数据存储的行程,并使数据模型和代码保持简单。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句