Hibernate and tables with same data/columns but with different table names

我们两清 提交于 2020-08-07 07:10:20

问题


The database I am working with has many tables with the same columns but with (obviously) different table names (I didn't design it). For example (these are database table names):

company1Data
company2Data
company3Data
etc.

Would it be possible to map these to one Java class entity with JPA and hibernate? The name of the class would be Data, and then pass in for example company1 somewhere when using it so that object would use the company1Data table?

Or is it better to just use normal, plain Java objects for something like this?

Thank you!


回答1:


Fundamentally, the problem here is a bad (really, terrible) database design. Ideally, you would simply fix this.

If you can't, I can see a couple of approaches.

One is to model this with inheritance, using a table per class mapping. You would make Data an abstract entity, then create trivial concrete subclasses mapped to each table. This would work, but would be inefficient for any queries not constrained to a particular class, because they will involve querying multiple tables, and will be awkward to use, because you need to work with a specific class for each table.

Another is to fix this with a view. Create a view which is the union of all the tables, and then map that. The problem here is that you won't be able to insert into it. You might be able to do something clever with triggers here, but it will depend on your database, and take more database and JPA wizardry than i have!




回答2:


In my opinion it's way more faster to you if you use Hibernate...

The big advantage of using JPA with Hibernate is you don't need to write some sql commands, like inserts and updates.

Here are some tutorials where you can start with Hibernate:

http://www.javacodegeeks.com/2012/05/tutorial-hibernate-jpa-part-1.html http://docs.jboss.org/hibernate/orm/3.6/quickstart/en-US/html/hibernate-gsg-tutorial-jpa.html

Hope it helped...

Here are some topics with people with the same problem:

How to map one class to different tables using hibernate/jpa annotations

JPA, How to use the same class (entity) to map different tables?



来源:https://stackoverflow.com/questions/16707540/hibernate-and-tables-with-same-data-columns-but-with-different-table-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!