如何在java中使用hibernate为crud操作创建一个通用方法

px9o7tmv  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(274)

我有一个带有hibernate的java项目。它包含两个类: Student 以及 Course .
现在我想为所有的方法创建一个泛型方法 create, update and delete 操作。我的最后一个学生管理代码是:

import org.hibernate.Session;
import org.hibernate.Transaction;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

public class ManageStudent extends Repository implements Serializable {

public static Student getStudent(Integer yourstcode) throws SQLException {
    Session session = OpenSession1();
    Student student = (Student) session.createQuery("from Student s where s.studentcode=:x").setParameter("x", yourstcode).uniqueResult();

    session.close();
    return student;
}
public static Student getStudentbyId(int stdNumber) throws SQLException {
    Session session = OpenSession1();
    Student student = (Student) session.createQuery("from Student s where s.id=:x").setParameter("x", stdNumber).uniqueResult();
    session.close();
    return student;
}

public static void addstudent(Student student) throws SQLException {
    Session session = OpenSession1();
    Transaction tx = session.beginTransaction();
    session.saveOrUpdate(student);
    tx.commit();
    CloseSession(session);

}

public static void deletestudent(Student studentd) throws SQLException {
    Session session = OpenSession1();
    Transaction tx = session.beginTransaction();
    session.delete(studentd);
    tx.commit();
    CloseSession(session);
}

public static List<Student> getAllStudents() throws SQLException {
    Session session = OpenSession1();
    List<Student> students = session.createQuery("from Student").list();
    CloseSession(session);
    return students;
}

public static void showStudents() throws SQLException {
    for (Student student : getAllStudents()) {
        System.out.println("StudentID: " + student.getId());
        System.out.println("Student Code: " + student.getStudentcode());
        System.out.println("FirstName: " + student.getFirstName());
        System.out.println("LastName:" + student.getLastName());
        System.out.println("FatherName: " + student.getFatherName());
        System.out.println("Age: " + student.getAge());
        System.out.println("Major: " + student.getMajor());
        System.out.println("------------------------------------");
    }
}

public static void updateStudent(Student student) throws SQLException {

    Session session = OpenSession1();
    Transaction tx = session.beginTransaction();

    session.saveOrUpdate(student);
    tx.commit();
    CloseSession(session);

}

public static void showStudent(Student student) throws SQLException {
    System.out.println(student.getFirstName());
    System.out.println(student.getStudentcode());
    System.out.println(student.getLastName());

    System.out.printf("|%10s|%10s|%10s|%n", "NAME", "FAM", "AGE");
    student.print();
}

}
现在我想写一个通用方法来完成所有的工作:例如:使用一个参数do update student,在数据库中为另一个add student和为另一个delete student。我读了关于抽象,接口和泛型,但我不明白我该怎么做。。。请帮帮我
这是我调用这些方法的swith案例。

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Run {
static Integer coursecode;
static Integer yourstcode;

private static SessionFactory factory;

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
        // builder pattern (design pattern)
        factory = new Configuration()
                .configure()
                .addAnnotatedClass(Student.class)
                .addAnnotatedClass(Course.class)
                .buildSessionFactory();

        while (true) {

            System.out.println("menu\n\n see student            1 \n see courses            2\n see your courses       3\n enter new student      4\n enter new course       5\n edit your profile      6\n delete a student       7\n delete  a course       8\n choose course          9");
            Integer i = Console.getInputInteger("\n\nplease select a number");

            switch (i) {
                case 1:
                    ManageStudent.showStudents();

                    break;
                case 2:
                    ManageCourse.showCourse();

                    break;
                case 3:
                    yourstcode = Console.getInputInteger("enter your code");
                    Collection<Course> course3= ManageCourse.getSelectedCourse(yourstcode);
                    ManageCourse.showCourseSelected(course3);

                    break;
                case 4:

                    yourstcode = Console.getInputInteger("enter your code");

                    int stage = Console.getInputInteger("enter your age");
                    String stname = Console.getInputString("enter your name:");
                    String stlname = Console.getInputString("enter your lastname:");
                    String stfname = Console.getInputString("enter your fathername:");
                    String stmajor = Console.getInputString("enter your major:");

                    Student student = new Student();
                    student.setFirstName(stname);
                    student.setLastName(stlname);
                    student.setAge(stage);
                    student.setFatherName(stfname);
                    student.setMajor(stmajor);
                    student.setStudentcode(yourstcode);
                    ManageStudent.addstudent(student);
                    ManageStudent.showStudents();
                    break;
                case 5:

                    coursecode = Console.getInputInteger("enter your code");
                    String coursename1 = Console.getInputString("enter name of lesson:");
                    int coursegrade1 = Console.getInputInteger("enter grade");
                    Course course1 = new Course();
                    course1.setCoursecode(coursecode);
                    course1.setCoursename(coursename1);
                    course1.setGrade(coursegrade1);
                    ManageCourse.addCourse(course1);
                    ManageCourse.showCourse();
                    break;

                case 6:
                    yourstcode = Console.getInputInteger("enter your code");

                    Student student2 = ManageStudent.getStudent(yourstcode);
                    ManageStudent.showStudent(student2);

                    System.out.println("-----------edit your profile-----------");
                    student2.setId(student2.getId());
                    student2.setStudentcode(Console.getInputInteger("enter your age"));
                    student2.setFirstName(Console.getInputString("enter your name:"));
                    student2.setLastName(Console.getInputString("enter your lastname:"));
                    student2.setFatherName(Console.getInputString("enter your fathername:"));
                    student2.setMajor(Console.getInputString("enter your major:"));

                    ManageStudent.updateStudent(student2);

                    ManageStudent.showStudents();
                    break;
                case 7:
                    yourstcode = Console.getInputInteger("enter your code");
                    Student studentd = ManageStudent.getStudent(yourstcode);
                    ManageStudent.deletestudent(studentd);
                    ManageStudent.showStudents();
                    break;

                case 8:
                    coursecode = Console.getInputInteger("enter your code");
                    Course coursed = ManageCourse.getCourse(coursecode);
                    ManageCourse.deleteCourse(coursed);
                    ManageCourse.showCourse();
                    break;
                case 9:

                    List<Student> students = ManageStudent.getAllStudents();
                    List<Course> courses = ManageCourse.getAllCourse();
                    Set<Course> courseList = new HashSet<>();
                    for (Student student1 : students) {
                        System.out.print(student1.getStudentcode());
                        System.out.println("StudentID: " + student1.getId());
                        System.out.println("StudentCode: " + student1.getStudentcode());
                        System.out.println("FirstName: " + student1.getFirstName());
                        System.out.println("LastName:" + student1.getLastName());
                        System.out.println("FatherName: " + student1.getFatherName());
                        System.out.println("Age: " + student1.getAge());
                        System.out.println("Major: " + student1.getMajor());
                        System.out.println("------------------------------------");
                    }

                    System.out.println("Enter studentid: ");
                int stdNumber = Console.getInputInteger("enter your code");

                    Student student1 = ManageStudent.getStudentbyId(stdNumber);

                    System.out.print("Courseid");
                    System.out.print("   coursename");
                    System.out.println("   grade");
                    for (Course course : courses) {
                        System.out.print(course.getId());
                        System.out.print("        " + course.getCoursename());
                        System.out.println("          " + course.getGrade());
                    }

                    System.out.println("Enter Number of Course Selection: ");
                    int numCourseSelection = Integer.parseInt(reader.readLine());

                    if (numCourseSelection != 0) {
                        for (int j = 1; j <= numCourseSelection; j++) {
                            System.out.println("Enter Course id" + j + ": ");
                            Course course = ManageCourse.getCourse( Integer.parseInt(reader.readLine()));
                            courseList.add(course);
                        }
                        student1.setCourses(courseList);
                    }
                    ManageCourse.Courseselection(student1);

            }
        }

    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object." + ex);
        throw new ExceptionInInitializerError(ex);
    }

}

}

lmvvr0a8

lmvvr0a81#

你可以设计你的 Student 分类如下-

public class Student {
    private Collection<Course> courses = new ArrayList<>();
.....................
.....................
}

使用 generic method 你可以设计 ManageStudent 等级如下-

public class ManageStudent{

    enum OPERATION {
        CREATE, UPDATE, DELETE
    }

    public static void doOperation(Student student, OPERATION op) {
        switch (op) {
        case CREATE: {
            System.out.println("perfrom create operation");
            break;
        }
        case UPDATE: {
            System.out.println("perfrom update operation");
            break;
        }
        case DELETE: {
            System.out.println("perfrom delete operation");
            break;
        }
        default:
            // throw some meaningful exception
        }
    }
}

相关问题