gpt4 book ai didi

java - 将 DAO 类制作为可比较类型是一个好的做法吗

转载 作者:行者123 更新时间:2023-11-30 02:19:19 25 4
gpt4 key购买 nike

这是我在 hibernate 中的示例映射

class ApplnDoc {
AdmAppln admAppln;
// getters and setters
}
<小时/>
class AdmAppln {
Set<Student> student;
// getters and setters
}
<小时/>
class Student {
int id;
String registerNo;
AdmAppln admAppln;
// getters and setters
}

ApplnDoc表我们存储所有候选人的图像。 AdmAppln用于存储入场详细信息,Student用于存储学生详细信息。即使AdmAppln正在有一个 SetStudent ,只有 Student 一条记录将出现在特定的 AdmAppln id (一个 AdmAppln 下只有一名学生)。

现在我想将一些数据写入这些表中,写入Excel文件,其记录必须按 registerNo 的顺序排序(如果存在),否则使用 id Student的。我们正在使用XSSFWorkbook类下 org.apache.poi.xssf.usermodel用于在 Excel 上执行操作的包床单。 Here我找到了一种对 Excel 工作表进行排序的方法,但我尝试使用 Comparable 在代码本身中找到了一种方法界面。

这就是我在 ApplnDoc 中所做的类

public int compareTo(ApplnDoc otherData) {
if(new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo() != null &&
!new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo().isEmpty() &&
new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo() != null &&
!new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo().isEmpty()) {

return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getRegisterNo()
.compareTo
(new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getRegisterNo());
} else {
return new ArrayList<Student>(this.admAppln.getStudents()).get(0).getId() -
new ArrayList<Student>(otherData.admAppln.getStudents()).get(0).getId();
}
}

因为没有get() Set中的方法接口(interface)是获取Student的唯一途径的registerNo来自AdmAppln是将其转换为列表。然后我对列表进行排序,然后迭代生成 Excel 文件。

上述比较机制是否合适或者是否有更好的方法?为什么我问这个问题是因为当 Hibernate session 关闭并且在我的 compareTo 中时如果我访问子表列,那么我将得到 Invocation异常。

最佳答案

这里有一些值得讨论的事情:

1-

Even if AdmAppln is having a Set of Student, only one record of Student will be present for a particular AdmAppln

为什么?这是您无法控制的事情,还是有任何特殊原因要在不需要的地方保留一套? (我还假设 @OneToMany 而不是 @OneToOne 映射)

2-

这会导致子对象被延迟获取(注意这是一个假设,因为您没有发布有关映射或如何从数据库获取实体的相关代码)。

这意味着您必须切换到实体中的急切获取(不推荐)或在获取实体时指定它

3-

另外请重构compareTo并使用变量

public int compareTo(ApplnDoc otherData) {
Student thisStudent = new ArrayList<>(this.admAppln.getStudents()).get(0);
Student otherStudent = new ArrayList<>(otherData.admAppln.getStudents()).get(0);
if(thisStudent.getRegisterNo() != null &&
!thisStudent.getRegisterNo().isEmpty() &&
otherStudent.getRegisterNo() != null &&
!otherStudent.getRegisterNo().isEmpty()) {
return thisStudent.getRegisterNo().compareTo(otherStudent.getRegisterNo());
} else {
return thisStudent.getId() - otherStudent.getId();
}
}

虽然该比较机制没有任何问题(如果您有一个空的学生Set,则 NullPointer 除外),但您应该在查询时使用数据库排序。

如果您仍然想以这种方式进行比较,您只需确保在关闭 session 之前已获取所需的所有内容。

关于java - 将 DAO 类制作为可比较类型是一个好的做法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47305952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com