spring hibernate的数据库每用户连接

时间:2016-03-22 17:03:52

标签: java spring hibernate jpa

我正在开发一个Spring JPA / Hibernate项目,它必须使用数据库用户的连接来实现持久性。

事实上,每个用户都有自己的Oracle数据库连接,我必须在应用程序中使用它来了解谁访问和写入我的数据库。

如何使用与Hibernate不同的数据库连接而不是使用单个应用程序连接(在applicationContext数据源中)?

1 个答案:

答案 0 :(得分:0)

了解AbstractRoutingDataSource和我的旧问题 AbstractRoutingDataSource change map in runtime
会话监听器:

public class SessionListener implements HttpSessionListener {
    @Autowired
    DataSourceMap dataSourceMap;
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        System.out.println("tworzenie sesji");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        System.out.println(httpSessionEvent.getSession().getId());
        dataSourceMap.removeSource(httpSessionEvent.getSession().getId());
    }
}

<强>路由:

@Component
public class CustomRoutingDataSource extends AbstractRoutingDataSource{
    @Autowired
    DataSourceMap dataSources;
    @Override
    protected Object determineCurrentLookupKey() {
        //setDataSources(dataSources);
        afterPropertiesSet();
        System.out.println("test");
        if( SecurityContextHolder.getContext().getAuthentication()!=null) {
            HttpServletRequest request = ((ServletRequestAttributes)
                    RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getSession().getId();
        }

        return "auth";
    }
    @Autowired
    public void setDataSources(DataSourceMap dataSources) {
        System.out.println("data adding");
        setTargetDataSources(dataSources.getDataSourceMap());
    }

}

<强>地图

@Component
@Scope(value = "singleton")
public class DataSourceMap {
    private Map<Object,Object> dataSourceMap;
    public DataSourceMap()
    {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.driverClassName("org.h2.Driver");
        dataSourceBuilder.url("jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
        dataSourceBuilder.username("sa");
        dataSourceBuilder.password("");
        dataSourceMap=new HashMap<Object,Object>();
        dataSourceMap.put("auth",dataSourceBuilder.build());
    }
    public void addDataSource(String session,DataSource dataSource)
    {
        this.dataSourceMap.put(session,dataSource);
    }
    public Map<Object,Object> getDataSourceMap()
    {
        return dataSourceMap;
    }
    public void removeSource(String session)
    {
        dataSourceMap.remove(session);
    }
}