首页 > 解决方案 > 使用额外列休眠多对多 xml 映射

问题描述

我正在尝试对休眠和与 xml 的关系进行一些练习,并且一切正常,但现在我想知道如何在我的连接表上实现额外的列,但我找不到方法。

这是我的代码:

成绩 hbm xml

<hibernate-mapping>
    <class name="Grade" table="Grades" catalog ="test">
        <id name="id">
            <column name = "id"/>
            <generator class="increment"/>
        </id>
        <property name ="name"></property>
        <property name ="code"></property>  
    </class>
</hibernate-mapping>

学生 hbm xml

<hibernate-mapping>
    <class name="Student" table="Students" catalog ="test">
        <id name="id">
            <column name = "student_id"/>
            <generator class="increment"/>
        </id>
        <property name ="name"></property>
        <property name="years" type ="integer"></property>
        <set name="grade" table="student_grades" cascade="all">
            <key column="student_id" not-null="true" />
            <many-to-many column="grade_id" class="Grade"/>           
        </set>  
    </class>
</hibernate-mapping>

等级.java

public class Grade implements Serializable{
    
    private Long id;
    private String name;
    private String code;

    public Grade () {
        
    }
    
    public Grade (String name, String code) {
        this.name= name;
        this.code= code;
    }

    getters and setters

学生.java

public class Student implements Serializable{
    
    private Long id;
    private String name;
    private int years;
    private Set<Grade> grade;
    
    public Student() {
        
    }
    
    public Student(String name, int years, Set<Grade> grade) {
        super();
        this.name= name;
        this.years= years;
        this.grade= grade;
    }

主要的

public class Main {
    public static void main(String[] args) {
        Configuration cfg =new Configuration().configure();
        SessionFactory sessionFactory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
        Session session = null;
        Transaction tx = null;
        
        try {
            session = sessionFactory.openSession();
            tx = session.beginTransaction();        
            
            Grade m1 = new Grade("Test A", "01");
            session.save(m1);

            HashSet<Grade> set1 = new HashSet<Grade>();
            set1.add(m1);
            Student a = new Student("Richard", 26, set1);
            session.save(a);
 
            ...

有了这个,我有一个名为“student_grades”的表,其中包含 student_id 和grade_id,每个学生的成绩都在其中,但我也想在该表上显示成绩名称和学生姓名。有什么办法吗?

谢谢

标签: javaxmlhibernatehibernate-mapping

解决方案


据我所知,连接表上的附加列对于多对多关系是不可能的。我猜你需要两个一对多的关系,并在你的数据库结构中手动添加 student_grades。

另外,也许看看这里:Mapping many-to-many association table with extra column(s)


推荐阅读