Hibernate ManyToOne 和 OneToMany 在一个实体中

发布于 2024-10-17 23:29:09 字数 4456 浏览 3 评论 0原文

我有 3 个表 University(id,name)、Group(id、name、university_id)、Student(id、name、number、group_id)。 一所大学有多个小组,一个小组有许多学生。

我的 POJO 看起来像这样:

@Entity(name = "Student")
public class Student {
    @SequenceGenerator(name = "genStudent",sequenceName = "STUDENTSEQ")
    @Id
    @GeneratedValue(generator = "genStudent")
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "facNum")
    private String facNum;
    @ManyToOne
    private UniGroup group;

    public UniGroup getGroup() {
        return group;
    }

    public void setGroup(UniGroup group) {
        this.group = group;
    }

    public Student(){
    }
... getters and setters
}

@Entity
public class UniGroup {
    @SequenceGenerator(name = "genGroup",sequenceName = "UNIGROUPSEQ")
    @Id
    @GeneratedValue(generator = "genGroup")
    private int id;
    @Column(name = "administrativeName")
    private String administrativeName;
    @OneToMany(mappedBy = "group",cascade=CascadeType.ALL)
    private List<Student> students;
    @ManyToOne
    private University university;
... getters and setters
}

@Entity
public class University {
    @SequenceGenerator(name = "genUniversity",sequenceName = "UNIVERSITYSEQ")
    @Id
    @GeneratedValue(generator = "genUniversity")
    private int id;
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "university",cascade=CascadeType.ALL)
    private List<UniGroup> groups;

    public University(){
        groups = new ArrayList<UniGroup>();
    }

我的助手类:

public class StudentSystemUtil {
    private SessionFactory sessFac;

    public StudentSystemUtil(){
        sessFac = new Configuration().configure().buildSessionFactory();
    }

    @SuppressWarnings("unchecked")
    public void showGroups(){
        Session session = sessFac.getCurrentSession();

        try{
        session.beginTransaction(); 

        Query q = session.createQuery("from UniGroup");

        List<UniGroup> groups = (List<UniGroup>)q.list();

        for(UniGroup g:groups){
            System.out.println("Group: "+g.getId()+" "+g.getAdministrativeName());
            for(Student s:g.getStudents()){
                System.out.println(s.getName()+" "+s.getGroup().getAdministrativeName());
            }
        }
        session.getTransaction().commit();
        }catch(Exception e){
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void saveGroup(UniGroup group){
        Session session = sessFac.getCurrentSession();
        try{
        session.beginTransaction();

        session.save(group);

        session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction() != null){
                session.getTransaction().rollback();
            }
            System.out.println("Error: "+e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public void showUniversityes(){
        Session session = sessFac.getCurrentSession();

        try{
        session.beginTransaction(); 

        Query q = session.createQuery("from University");

        List<University> universityes = (List<University>)q.list();

        for(University u:universityes){
            System.out.println("University: "+u.getId()+" "+u.getName());
            for(UniGroup g:u.getGroups()){
                System.out.println(g.getAdministrativeName());
                for(Student s:g.getStudents()){
                    System.out.println("Student "+s.getName());
                }
            }
        }
        session.getTransaction().commit();
        }catch(Exception e){
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void saveUniversity(University uni){
        Session session = sessFac.getCurrentSession();
        try{
        session.beginTransaction();

        session.save(uni);

        session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction() != null){
                session.getTransaction().rollback();
            }
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void closeSessionFactory(){
        sessFac.close();
    }

}

我会得到

Error: Could not execute JDBC batch update
Error: could not execute query

当我尝试保存或显示某些内容时, 。请帮忙。

I have 3 tables University(id,name), Group(id,name,university_id), Student(id,name,number,group_id).
One university have many groups and one group have many students.

My POJOs look like this:

@Entity(name = "Student")
public class Student {
    @SequenceGenerator(name = "genStudent",sequenceName = "STUDENTSEQ")
    @Id
    @GeneratedValue(generator = "genStudent")
    private int id;
    @Column(name = "name")
    private String name;
    @Column(name = "facNum")
    private String facNum;
    @ManyToOne
    private UniGroup group;

    public UniGroup getGroup() {
        return group;
    }

    public void setGroup(UniGroup group) {
        this.group = group;
    }

    public Student(){
    }
... getters and setters
}

@Entity
public class UniGroup {
    @SequenceGenerator(name = "genGroup",sequenceName = "UNIGROUPSEQ")
    @Id
    @GeneratedValue(generator = "genGroup")
    private int id;
    @Column(name = "administrativeName")
    private String administrativeName;
    @OneToMany(mappedBy = "group",cascade=CascadeType.ALL)
    private List<Student> students;
    @ManyToOne
    private University university;
... getters and setters
}

@Entity
public class University {
    @SequenceGenerator(name = "genUniversity",sequenceName = "UNIVERSITYSEQ")
    @Id
    @GeneratedValue(generator = "genUniversity")
    private int id;
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "university",cascade=CascadeType.ALL)
    private List<UniGroup> groups;

    public University(){
        groups = new ArrayList<UniGroup>();
    }

My helper class:

public class StudentSystemUtil {
    private SessionFactory sessFac;

    public StudentSystemUtil(){
        sessFac = new Configuration().configure().buildSessionFactory();
    }

    @SuppressWarnings("unchecked")
    public void showGroups(){
        Session session = sessFac.getCurrentSession();

        try{
        session.beginTransaction(); 

        Query q = session.createQuery("from UniGroup");

        List<UniGroup> groups = (List<UniGroup>)q.list();

        for(UniGroup g:groups){
            System.out.println("Group: "+g.getId()+" "+g.getAdministrativeName());
            for(Student s:g.getStudents()){
                System.out.println(s.getName()+" "+s.getGroup().getAdministrativeName());
            }
        }
        session.getTransaction().commit();
        }catch(Exception e){
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void saveGroup(UniGroup group){
        Session session = sessFac.getCurrentSession();
        try{
        session.beginTransaction();

        session.save(group);

        session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction() != null){
                session.getTransaction().rollback();
            }
            System.out.println("Error: "+e.getMessage());
        }
    }

    @SuppressWarnings("unchecked")
    public void showUniversityes(){
        Session session = sessFac.getCurrentSession();

        try{
        session.beginTransaction(); 

        Query q = session.createQuery("from University");

        List<University> universityes = (List<University>)q.list();

        for(University u:universityes){
            System.out.println("University: "+u.getId()+" "+u.getName());
            for(UniGroup g:u.getGroups()){
                System.out.println(g.getAdministrativeName());
                for(Student s:g.getStudents()){
                    System.out.println("Student "+s.getName());
                }
            }
        }
        session.getTransaction().commit();
        }catch(Exception e){
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void saveUniversity(University uni){
        Session session = sessFac.getCurrentSession();
        try{
        session.beginTransaction();

        session.save(uni);

        session.getTransaction().commit();
        }catch(Exception e){
            if(session.getTransaction() != null){
                session.getTransaction().rollback();
            }
            System.out.println("Error: "+e.getMessage());
        }
    }

    public void closeSessionFactory(){
        sessFac.close();
    }

}

And i get

Error: Could not execute JDBC batch update
Error: could not execute query

when try to save or show something. Help please.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隐诗 2024-10-24 23:29:09

您应该做的第一件事是在应用 @ManyToOne 的地方添加 @JoinColumn 注释,否则将应用默认值。 @JoinColumn 有参数名称,指定数据库中的哪一列用于关系。
有关详细信息,请参阅文档

First thing you should do is to add @JoinColumn annotation where @ManyToOne is applied, because otherwise default will be applied. @JoinColumn has parameter name which specify which column in database is used for relationship.
Have a look at documentation for more info

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文