【发布时间】:2014-05-06 12:09:49
【问题描述】:
我使用 JPA 注释在部门和员工之间创建了拥有的一对多关系。 实体是:
Department(Parent)
String Id
String Name
List Employee(@OneToMany)
Employee(Child)
Key key
String firstName
String lastName
String Address
Department dept(@ManyToOne)
当输入员工的名字时,我想显示该员工的详细信息(姓氏和地址)以及他所属的部门。我没有找到任何解决方案来从子实体获取父信息。有没有办法从其子实体中获取有关父实体的信息?
我认为一种可能的解决方案是从孩子那里获取父 ID,然后在另一个查询中获取父详细信息。但我想在单个查询中获得有关员工的所有信息。这可能吗?
这是我的代码。
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();
}
【问题讨论】:
标签: java google-app-engine jpa google-cloud-datastore one-to-many