简体   繁体   中英

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

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!

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!

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?

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