2

I have multiple tables in a MySQL database. Lets say they look like this:

  • Book:

    title, subject, publisher, book_author
    
  • Journal:

    title, subject, publisher, journal_name
    
  • Blog:

    title, subject, website, blog_author
    
  • ENews:

    title, subject, website, news_paper_name
    

The particular structure is irrelevant to the problem. In reality, there are around 20 columns that all of the tables share and more that are unique to a few or just one table. The point is, they all share some columns. I want to use Hibernate to access these, using annotated classes. I don't want to have 5+ classes that each have 20+ redundant fields, each with an accessor and mutator. I would like a class structure something like this:

  • abstract Publication { title, subject }
    • abstract PrintPublication { publisher }
      • Book { book_author }
      • Journal { journal_name }
    • abstract Online Publicaiton { website }
      • Blog { blog_author }
      • ENews { news_paper_name }

However, I can't for the life of me figure out how to get this to work. Each of the concrete classes is a single table in the database. I thought the solution would be a table per class (@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)), but that threw a number of interesting errors.

What is the proper solution to all of this? Besides altering the table structure. The database is not mine and I have not been given rights to change it.

4

1 回答 1

4

If there is no need for type inheritance between entities, for that purpose there is MappedSuperClass. Idea is that you define all the common persistent attributes and their mappings in mapped superclass and entities will extends it.

Result is that mappings will apply to entity that extends mapped superclass, but from the point-of-view of persistence there is not is-a relationship between entity and mapped superclass.

Following provides starting point:

@MappedSuperclass
public class Publication {
    String title;
    @Column (name="subject_of_publication")
    String subject;

    ...
}

@MappedSuperclass
public class PrintPublication extends Publication {
    String publisher;
    ...
}

@Entity
public class Book extends PrintPublication {//inherits persistent attributes
    ...
    String author;
}

You can also have mapped superclasses in other levels in entity hierarchy and override mappings in entities as needed.

But if you have to in some point threat for example Book and Blog as one type, then mapped superclass is not way to go, because you cannot query it.

于 2012-06-15T20:34:36.183 回答