How to use Hibernate @Any-related annotations?

前端 未结 4 1162
抹茶落季
抹茶落季 2020-11-27 16:56

Could someone explain to me how Any-related annotations (@Any, @AnyMetaDef, @AnyMetaDefs and @ManyToAny) work in practice

4条回答
  •  忘掉有多难
    2020-11-27 17:22

    The @Any annotation defines a polymorphic association to classes from multiple tables, right, but polymorphic associations such as these are an SQL anti-pattern! The main reason is that you can´t define a FK constraint if a column can refer to more than one table.

    One of the solutions, pointed out by Bill Karwin in his book, is to create intersection tables to each type of "Any", instead of using one column with "type", and using the unique modifier to avoid duplicates. This solution may be a pain to work with JPA.

    Another solution, also proposed by Karwin, is to create a super-type for the connected elements. Taking the example of borrowing Book, DVD or VHS, you could create a super type Item, and make Book, DVD and VHS inherit from Item, with strategy of Joined table. Borrow then points to Item. This way you completely avoid the FK problem. I translated the book example to JPA bellow:

    @Entity
    @Table(name = "BORROW")
    public class Borrow{
    //... id, ...
    @ManyToOne Item item;
    //...
    }
    
    @Entity
    @Table(name = "ITEMS")
    @Inheritance(strategy=JOINED)
    public class Item{
      // id, ....
      // you can add a reverse OneToMany here to borrow.
    }
    
    @Entity
    @Table(name = "BOOKS")    
    public class Book extends Item {
      // book attributes
    }
    
    @Entity
    @Table(name = "VHS")    
    public class VHS extends Item {
      // VHSattributes
    }
    
    @Entity
    @Table(name = "DVD")    
    public class DVD extends Item {
      // DVD attributes
    }
    

提交回复
热议问题