[英]How do I map tables to Java objects
舉個例子,我有三個這樣的表。 數據庫圖像我如何將第三個表映射到 java 對象。
class StudentCourse{
Student student;
Course course;
Double score;
}
或者
class StudentCourse{
Long studentId;
Long courseId;
Double score;
}
如果我使用第一個,在我更新數據庫中的一些數據(例如學生信息)后。下次我從數據庫(我使用 mybatis)查詢 StudentCourse 時,緩存會導致數據不正確嗎? 如果我使用第二個,如果我想列出學生的課程成績,我必須先查詢 StudentCourse 列表,然后通過 courseId 從數據庫中查詢課程信息,對於每個結果我需要額外的查詢。 我認為這會降低程序的效率。 有沒有其他方法可以解決這個問題?
對於第一個。 mybatis第二次做查詢,如果數據還沒有更新,會從緩存中獲取結果。
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
this.localCache.putObject(key, ExecutionPlaceholder.EXECUTION_PLACEHOLDER);
List list;
try {
list = this.doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
this.localCache.removeObject(key);
}
this.localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
this.localOutputParameterCache.putObject(key, parameter);
}
return list;
}
如果我有這樣的 resultMap
<resultMap id="studentcourse" type="StudentCourse">
<association property="student" resultMap="Student" />
<association property="course" resultMap="Course"/>
<result property="score" column="score"/>
</resultMap>
首先,我從數據庫中獲取一個 StudentCourse 對象,localCache 緩存該對象。然后我更新 StudentCourse 中的 Course(更改數據庫記錄)。第二次我獲取一些 StudentCourse 時,它將從 localcache 返回一個結果。所以StudentCourse中的課程信息是臟數據,選擇第一個怎么處理。
理想情況下,您將使用一種類設計,它可以最好地為您的域建模,並擔心映射到單獨持久層中的數據存儲。 如果您需要大幅更改模型以允許持久層發揮作用,那么您需要一個新的 ORM! 雖然我不熟悉 mybatis,但我希望它不會在每次更改基礎數據時都創建一個新對象。
course
和student
表中的鍵充當student_course
表中的外鍵。 外鍵在 Java 中最好表示為引用。 在 Java 級別使用密鑰會強制使用額外的間接級別,並使您面臨完整性問題(例如,如果外鍵更改)。
所以我建議:
class StudentCourse {
private final Student student;
private final Course course;
private double score;
}
您還可以考慮將它放在其他類之一中 - 這可能更方便,具體取決於類的使用方式:
class Student {
private final int id;
private String name;
private List<CourseScores> scores = new ArrayList<>();
public void addCourseScore(Course course, double score) {
scores.add(new CourseScore(course, score));
}
private record CourseScores(Course course, double score) { };
}
如果您的 ORM 沒有為您解析鍵(即在檢索數據時自動查找引用的對象),那么您需要自己做。 然而,這是一個非常簡單的對象:
class College {
private Map<Integer,Student> students;
private Map<Integer,Course> courses;
}
因此,將student_course
數據轉換為上述模型的代碼可能如下所示:
ResultSet data;
while (!data.isAfterLast()) {
Student student = college.getStudent(data.getInteger("student"));
Course course = college.getCourse(data.getInteger("course"));
double score = data.getDouble("score");
student.addCourseScore(course, score);
data.next();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.