简体   繁体   中英

Spring-Hibernate, Many to Many relationship query

I have two bean classes Student and Course which has many to many relationship with each other. For eg. one student can register for multiple courses and vice versa. I have used HibernateTemplate to save objects into Oracle DB. Following are Student, Course and StudentDao classes.

Student Class

package com.springhibernate;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="Student")

public class Student {
    private int studentId;
    private String firstName;
    private String lastName;
    private Set<Course> courses;

@Id
@Column(name="student_id")
public int getStudentId() {
    return studentId;
}
public void setStudentId(int studentId) {
    this.studentId = studentId;
}

@Column(name="first_name")
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}

@Column(name="last_name")
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Student_Course", joinColumns = @JoinColumn(name = "student_id"), inverseJoinColumns = @JoinColumn(name = "course_id"))
public Set<Course> getCourses() {
    return courses;
}
public void setCourses(Set<Course> courses) {
    this.courses = courses;
}

}

StudentDao class

package com.springhibernate;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDao {

private static Helper helper = new Helper();

HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
    this.template = template;
}

// method to save student
public void saveStudent(Student s) {
    template.save(s);
}

// method to return one employee of given id
public Student getById(int id) {
    Student s = (Student) template.get(Student.class, id);
    return s;
}

public List<Course> findCourse(){
    List<Course> list = template.find("from Course");
    return list;
}
}

Course Class

package com.springhibernate;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;


@Entity
@Table(name="Course")
public class Course {

private int courseId;
private String courseName;
private Set<Student> students;

@Id
@Column(name="course_id")
public int getCourseId() {
    return courseId;
}
public void setCourseId(int courseId) {
    this.courseId = courseId;
}

@Column(name="course_name")
public String getCourseName() {
    return courseName;
}
public void setCourseName(String courseName) {
    this.courseName = courseName;
}

@ManyToMany(cascade=CascadeType.ALL,mappedBy="courses")
public Set<Student> getStudents() {
    return students;
}
public void setStudents(Set<Student> students) {
    this.students = students;
}

@Override
public int hashCode() {
    // TODO Auto-generated method stub
    return this.courseId;
}

@Override
public boolean equals(Object o) {
    // TODO Auto-generated method stub
    Course temp = (Course) o;
    return (this.courseId==temp.courseId);

}
}

I have following two queries

  1. I am able to save data in student_course table successfully. I was wondering if I want to retrieve data from student_course table, how can I do it using HibernateTemplate or is there any other way to do so? For example, query is like

     select course_id from student_course where student_id=1 

    Please note I want just the course id column not complete row.

  2. If in student_course table I want one more column say course_name (from course table), how can I do that?

You can do it in the following way, but keep in mind that the HibernateTemplate is an old API and you should use for example the EntityManager(Factory). You can get it via the Peristence class.

hibernateTemplate.execute(new HibernateCallback<List>() {

    public String doInHibernate(Session s)
            throws HibernateException, SQLException {
        SQLQuery sql=s.createSQLQuery("select course_id from student_course where student_id=?");
            sql.setParameter(0, adventureId);
        sql.addScalar(studentID);
        return sql.list();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM