weixin_42217783
nowayyyyy
2021-03-18 23:29
采纳率: 100%
浏览 28
已采纳

关于hibernate和hashset的一个问题

String hql = "FROM Student s JOIN s.modules m where m.moduleCode = :moduleCode"; 有一个这样的代码这个m应该是一个hashset它里面存的是一个类的对象所以我觉得这样直接点他是不对的应为这个modeCode是个属性而这个m是hashset没有这样的属性 

//课程表

@Entity
@Table(name = "MODULE")
public class Module {

    @Id
    @Column(name = "module_code")
    private String moduleCode;

    @Column(name = "module_name")
    private String moduleName;

    @ManyToMany(mappedBy = "modules")
    private Set<Student> students = new HashSet<>();

    public Module() {}

    public Module(String moduleCode, String moduleName) {
        this.moduleCode = moduleCode;
        this.moduleName = moduleName;
    }

    public String getModuleCode() {
        return moduleCode;
    }

    public String getModuleName() {
        return moduleName;
    }

    public void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Module{" +
                "moduleCode='" + moduleCode + '\'' +
                ", moduleName='" + moduleName + '\'' +
                '}';
    }
}

//学生表

package relationships.manytomany;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "STUDENT")
public class Student {

    @Id
    @Column(name = "student_id")
    private String studentId;

    @Column(name = "student_name")
    private String name;

    @Column(name = "student_age")
    private Integer age;

    @ManyToMany
    @JoinTable(
            name = "STUDENT_MODULE",
            joinColumns = {@JoinColumn(name = "student_id")},
            inverseJoinColumns = {@JoinColumn(name = "module_code")})
    private Set<Module> modules = new HashSet<>();

    public Student() {}

    public Student(String studentId, String name, Integer age) {
        this.studentId = studentId;
        this.name = name;
        this.age = age;
    }

    public String getStudentId() {
        return studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }


    public void setAge(Integer age) {
        this.age = age;
    }

    public Set<Module> getModules() {
        return modules;
    }

    public void setModules(Set<Module> modules) {
        this.modules = modules;
    }


    @Override
    public String toString() {
        return "Student{" +
                "studentId='" + studentId + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

//中间表

package relationships.manytomany;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import utility.HibernateUtil;

import java.util.*;

public class ManyToManyMain {

    public static void main(String[] args) {

        Session session = null;

        // create objects
        Student s1 = new Student("b1234", "Becky",19);
        Student s2 = new Student("b4321", "Jane",18);
        Student s3 = new Student("b4654", "Laura",22);
        Student s4 = new Student("b3541", "Rich",18);

        Set<Student> sl = new HashSet<>(Arrays.asList(s1,s2,s3,s4));

        Module m1 = new Module("csc1031", "Math");
        Module m2 = new Module("csc1032", "Arch");
        Module m3 = new Module("csc1033", "DB");
        Module m4 = new Module("csc1034", "P1");
        Module m5 = new Module("csc1035", "P2");

        Set<Module> ml = new HashSet<>(Arrays.asList(m1,m2,m3,m4,m5));


        // Create
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();

            // save objects to database
            for (Student stu : sl) {
                session.persist(stu);
            }
            for (Module mod : ml) {
                session.persist(mod);
            }

            // create relationship in student and save again
            // modules did not exist when first saved
            for (Student stu : sl) {
                stu.setModules(ml);
                session.persist(stu);
                
            }


            session.getTransaction().commit();

        } catch (HibernateException e) {
            if (session != null) session.getTransaction().rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

//查询

package querying.relationships;

import org.hibernate.Session;
import org.hibernate.query.Query;
import relationships.manytomany.Student;
import relationships.manytomany.Module;
import utility.HibernateUtil;

import java.util.List;

public class JoinQueries {
/*
    // one-to-one should be similar to this
    public static void oneToMany(){
        Session s = HibernateUtil.getSessionFactory().openSession();

        // Find what menu each item is on
        //String hql = "SELECT i.itemName FROM ITEM i";
        String hql = "SELECT i.itemName, m.name FROM MENU_ITEM i JOIN MENU m ON i.menu.id = m.id";

        s.beginTransaction();

        // Perform query
        Query query =  s.createQuery(hql);

        // Get results
        List results = query.list();

        s.getTransaction().commit();

        // Print results
        Object[] items = results.toArray();
        for (Object item : items) {
            //Object[] parts = (Object[]) items[i];
            //for (int j = 0; j < parts.length ; j++) {
            //System.out.print(parts[j]+" ");
            //}
            System.out.println(item);
        }
    }*/

    public static void manyToManyStudentsTakingMaths(String mc){
        Session s = HibernateUtil.getSessionFactory().openSession();
        // Find all students who take CSC1031
        //s.modules=m
        String hql = "FROM Student s JOIN s.modules m where m.moduleCode = :moduleCode";

        s.beginTransaction();

        // Perform query
        Query query =  s.createQuery(hql);
        query.setParameter("moduleCode",mc);

        // Get results - returns Collection of Collection (Student, Module)
        List<Student> results = query.list();

        s.getTransaction().commit();

        // Print results
        Object[] items = results.toArray();
        for (Object item : items) {
            Object[] parts = (Object[]) item;
            Student student = (Student) parts[0];
            Module module = (Module) parts[1];
            System.out.println(student + " -> " + module);
        }
    }

 /*   public static void manyToManyStudentModule(){
        Session s = HibernateUtil.getSessionFactory().openSession();

        // Find all mappings in STUDENT_MODULE
        String hql = "FROM Student s JOIN s.modules m where m.moduleCode IN (SELECT n.moduleCode FROM Module n)";

        s.beginTransaction();

        // Perform query
        Query query =  s.createQuery(hql);

        // Get results - returns Collection of Collection (Student, Module)
        List<Student> results = query.list();

        s.getTransaction().commit();

        // Print results
        Object[] items = results.toArray();
        for (int i = 0; i <items.length ; i++) {
            Object[] parts = (Object[]) items[i];
            Student student = (Student) parts[0];
            Module module = (Module) parts[1];
            System.out.println(student + " -> " + module);
        }
    }*/

    public static void main(String[] args) {
        //oneToMany();
        manyToManyStudentsTakingMaths("csc1032");
        //manyToManyStudentModule();
    }
}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • w2298119289j
    哆啦A梦丶幻想 2021-03-19 11:07
    已采纳
    String hql = "FROM Student s JOIN s.modules m where m.moduleCode = :moduleCode"; 
    有一个这样的代码,这个m应该是一个hashset。
    它里面存的是一个类的对象,所以我觉得这样直接点它,是不对的。
    因为这个modeCode是个属性,而这个m是hashset没有这样的属性

    首先,要讨论问题的话。需要先把问题描述清楚。

     

    SQL如果前面拼接了,“select s” 的语句话是没问题的

    这个SQL翻译为原生SQL就是:

    select s from student s

    INNER JOIN <student 和 module的关系表> sm  ON s.id = sm.student_id

    INNER JOIN module m ON m.id = sm.module_id

    WHERE  m.moduleCode = :moduleCode;

     

     

    m就是module的别名

    点赞 1 评论
  • weixin_42534024
    何必要如此 2021-03-19 10:06

    你觉你的sql写的很对?join后面是join字段?

    点赞 评论
  • weixin_42217783
    nowayyyyy 2021-03-19 12:26

    这个是hql不是sql不懂hql hibernate别来装冲ok?反正问题解决了csdn都这水平?

    点赞 评论
  • weixin_48029895
    慢慢走~ 2021-03-19 16:13

    你好,我是问答小助手,本次您提出的有问必答问题,已经由其他小伙伴为您做出解答,并解决了您的问题。

    本次提问扣除的有问必答次数,已经为您补发到账户,我们后续会持续优化,扩大我们的服务范围,为您带来更好地服务。

    点赞 评论
  • w2298119289j
    哆啦A梦丶幻想 2021-03-19 16:20

    另外,JPA查询的话建议看看我这篇文章。

     

    https://blog.csdn.net/w2298119289j/article/details/108883025?spm=1001.2014.3001.5502

    点赞 评论

相关推荐