Joh*_*aum 10 java design-patterns jdbc java-8
我有一个db设计问题,我正面对我的一个项目.我正在尝试实现一项服务,该服务的一部分是数据库层.它的设置使得我有一个帮助程序类,它们对数据库执行get/update方法,并在它们之上创建一个作为清理程序的层.例如:
public class GetStudentDBHelper {
public List<Student> get(List<Integer> ids) {
Conn getConnection...
// run sql query and construct returning Student objects
}
public List<Student> get(List<Classroom> byClassroom) {
// get all students in passed in classrooms
// run sql query and construct returning Student objects
}
}
public class StudentJanitor {
public GetStudentDBHelper getStudentDBHelper;
public UpdateStudentDBHelper updateStudentDBHelper;
public UpdateClassroomDBHelper updateClassroomDBHelper;
public List<Student> getStudents(List<Integer> ids) {
return getStudentDBHelper.get(ids);
}
public void saveStudents(List<Students> students, int classRoomid) {
Connection conn = Pool.getConnection(); // assume this gives a jdbc
conn.autocommit(false);
try {
try
{
updateStudentDBHelper.saveForClassroom(students, classRoomid, conn);
updateClassroomDBHelper.markUpdated(classRoomid, conn);
conn.commit();
}
catch
{
throw new MyCustomException(ErrorCode.Student);
}
}
catch (SQLException c)
{
conn.rollback();
}
finally {
conn.close();
}
}
public class ClassroomJanitor{
public void saveClassRoon(List<Classrooms> classrooms) {
Connection conn = Pool.getConnection()// assume this gives a jdbc
conn.autocommit(false);
try {
try {
updateClassroomDBHelper.save(classrooms, conn);
updateStudentDBHelper.save(classrooms.stream().map(Classroom::getStudents).collect(Collections.toList()), conn);
conn.commit();
}
catch {
throw new MyCustomException(ErrorCode.ClassRoom);
}
}
catch (SQLException c)
{
conn.rollback();
}
finally {
conn.close();
}
}...
public class GetClassroomDBHelper{}...
public class UpdateClassroomDBHelper{}...
Run Code Online (Sandbox Code Playgroud)
更新db类所有组成多个其他更新器,以防需要更新其他表中的值(即保存学生意味着我必须触摸学生所属的教室表,例如更新其上次更新的时间).
我遇到的问题是更新db类,如果我触及多个表以获得事务及其回滚功能,我必须从我的Janitor类传递连接.见上文我的意思.有一个更好的方法吗?这种类型的try,catch,conn传递给db帮助程序,必须在我的门卫中进行任何多事务操作.
简而言之,您可以看到代码通常在多个方法中重复:
Connection conn = Pool.getConnection()// assume this gives a jdbc
conn.autocommit(false);
try {
try {
//do some business logic requiring Connection conn
}
catch {
throw new MyCustomException(ErrorCode);
}
}
catch (SQLException c)
{
conn.rollback();
}
finally {
conn.close();
}
Run Code Online (Sandbox Code Playgroud)