简体   繁体   中英

Hibernate Single Table Hierarchy

I'm still learning Hibernate (jpa annotation) with Spring, but is there a way I would be able to take a single table and output hierarchical structure? Eg, I have a table called 'books' with the columns: book_id, author, library, floor, section. Is there a way I could return it with library -> floor -> section -> all the books in that section.

I have a class called books that essentially provides the everything required for creating the table. I also created a controller that lets me retrieve all the books, and it outputs it onto the webpage in a JSON format. Is there a way I could do this so it'll be hierarchical.

My first thought would be to make classes called library, floor, and section. Library would hold the name of the library and a list of floors in that library, floor would hold hold the name of the floot and a list of sections in that floor, and section would hold the name of the section and a list of all the books in that section. It became very long and involved, and I couldn't even get it to work, so I was hoping there was a much simpler way of doing it.

Yes there is, you can map ORM hierarchy in one of 3 ways, single table, one per concrete class and one per relationship.

For single table you have to use a discriminator column in the table that differentiates data and tells what row is for which object. Refer: http://www.thejavageek.com/2014/05/14/jpa-single-table-inheritance-example/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM