Hibernate or iBatis or something else?

后端 未结 3 1870
耶瑟儿~
耶瑟儿~ 2021-01-14 10:57

In my project i need to switch between databases during runtime. I tried to use Hibernate, but stuck in a place, where i need to map object with table in database. The probl

3条回答
  •  借酒劲吻你
    2021-01-14 11:52

    Working with dynamic table names is trivial in Ibatis. Just use expressions like:

    SELECT * FROM $tableName$
    

    where tableName is a property on the parameter class.

    Working with dynamic table names in Hibernate (or any JPA provider) is extraordinarily difficult if not impractical (or even impossible). This question has come up before. See JPA: How do I specify the table name corresponding to a class at runtime?.

    Working with dynamic data sources in Ibatis will require you to write some code but not all that much. Basically, Ibatis works around the concept of a sqlMapClient, which has a data source and a list of queries that it can run. Just create one sqlMapClient for each database, each with a different data source, and have them include all the same query files (in the sql map config).

    A DAO can be written such that it has multiple sqlMapClients injected and it selects which one to use at runtime. This is the part you'll have to write yourself but it's straightforward.

    This is predicated on knowing the databases at compile-time. If the database isn't known until runtime then that's a little harder. It might still be possible but I'm not sure how Ibatis will react if you basically swap data sources at runtime from the sqlMapClient. It might work, it might blow up. You'll have to try it and see.

    Hibernate may work here too along the same principle: you inject multiple persistence units into a DAO and use the right one at runtime. With Hibernate (or any JPA provider) you will have to watch out for making sure your managed objects are stored in the correct persistence unit. I can easily see this turning into a nightmare actually.

    One general comment: it's not advised to go down the path of dynamic table names or databases so really consider what you're doing and why and ask yourself if this could be remedied by making some better design choices.

提交回复
热议问题