插入具有属性关系的ManyToMany方法

时间:2014-05-27 19:03:11

标签: hibernate refactoring many-to-many hibernate-mapping cascade

我有一个超出外键的关联表,还有三个我需要保存的属性。

使用常见的ManyToMany关系,我可以使用Hibernate框架很简单地管理这种情况:

    @Entity
    @Table(name = "tb_table1")
    public class Table1 implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_table1", unique = true, nullable = false)
    private Long id;

    @ManyToMany
    @LazyCollection(LazyCollectionOption.FALSE)
    @JoinTable(name = "ta_association_table", 
            joinColumns =@JoinColumn(name = "id_table1"), 
            inverseJoinColumns =@JoinColumn(name = "id_table2"))
    private List<Object2> object2List;

//more code

我怀疑在哪里可以设置其他属性?

我找不到这个答案,这让我得到另一个解决方案:

协会类:

@Entity
@Table(name = "tb_association_table")
    public class AssociationTable implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="idl",nullable=false)  
    private Long id;

    @ManyToOne
    @JoinColumn(name="id_table1", nullable=false)
    private Table1 table1;

    @ManyToOne
    @JoinColumn(name="id_table2", nullable=false)
    private Table2 table2;

    @ManyToOne
    @JoinColumn(name="id_att1", nullable=false)
    private Attribute1 att1;

    @Column(name="id_att2", nullable=false)
    private Attribute2 att2 = true;

    //getters and setters

其他类非常相似:

@Entity
@Table(name = "tb_table1")
public class Table1 implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_table1", nullable=false)
    private Long id;

    @Column(unique=true, nullable=false)
    private String description;

    private boolean status = true;

    //getters and setters

最后我的插入方法:

public void insert(AssociationClass associationClass, List<Table2> table2List) {

   if (associationClass != null && associationClass.getTable1() != null) {

      if (table2List != null && table2List.size() > 0) {

         table1Service.insert(associationClass.getTable1());

            for (Table2 tbl2 : table2List) {

        AssociationClass newAC = new AssociationClass();
        newAC.setId(null);
        newAC.setAtt1(associationClass.getAtt1());
           newAC.setAtt2(associationClass.getAtt2);
        newAC.setAtt3(associationClass.getAtt3());
        newAC.setTable1(associationClass.getTable1());
           newAC.setTable2(tbl2);

        super.insert(newAC);
          }

    } 
    }

}

特别是我不喜欢这段代码,因为它不直观。我认为保持这种状态会变得困难。

1 个答案:

答案 0 :(得分:0)

据我所知,它不可能做你想做的事。您必须创建一个中间类(就像您一样)并将属性放在其上。

Attributes on Many-to-Many relationships (Hibernate)