如何使用Hibernate进行CRUD操作在java中创建泛型方法

时间:2018-05-12 08:07:28

标签: java mysql hibernate generics polymorphism

我有一个带hibernate的java项目。它包含两个类:StudentCourse

现在我想为所有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();
}

}

现在我想写一个完成所有工作的通用方法:例如:用一个参数做更新学生,另一个用数据库添加学生,另一个删除学生。我读到了抽象,界面和通用,但我不明白我应该做什么......请帮助

这是我调用这些方法的情况。

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);
    }


}

}

0 个答案:

没有答案