问题
I am working on a JavaEE project with WildFly
, Hibernate
(JPA
), C3P0
and a MS SQL Server
database.
The database is a legacy database with more than a thousand Database Objects like Stored Procedures
, Functions
, Views
, Triggers
and so on. All these database Objects have fine grained Permissions set on User Role
level.
Now I need to access this database with a JavaEE Web Application. My Problem is, that the usual JPA configuration let me set only one Username/Password for the Database in the configuration file. I can not find any way to configure the JPA layer so that will access the DB with the Enduser's Login.
I ended up to create one EntityManagerFactory per User by calling
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory(properties_with_credentials_here)
once per user.
The problem with this approach is, that this will basically instantiate the whole JPA layer per User and eat up way too much memory. I am not using any sort of Cache layer, of course. The memory is used just for the Entities meta information (which is a lot).
Now my original question: Is there any 'standard' way in JavaEE (JPA) to access the database layer with the Enduser's Login and Password?
I can not believe that I am the first person to encounter this situation. It seems to me, that 'impersonation' is quite normal in .net
Web Applications. So there must be way to do this in Java, i guess.
Any comments or hints or new approaches are highly welcome.
回答1:
The 'standard' way in JavaEE is to have an application user for accessing the database and achieve user-based access-rights through roles in your application.
If you need to rely on existing database user, your only chance is to establish a connection per user or per request. The entity manager would then indeed consume some memory as it's designed to be your application's persistence context (and thus some sort of cache).
Maybe you can have some trade-off here by accessing those parts which really have to be user-based by plain JDBC and potential execution of database procedures and others by some application user with extended rights which ensures the necessary user restrictions programmatically.
来源:https://stackoverflow.com/questions/50755414/accessing-the-database-via-jpa-with-the-endusers-credentials-in-java-ee