Hibernate 4: Multitenacy alguém conseguiu implementar?

0 respostas
Marques

Colegas,

Tendo como base esse tutorial [url] www.devx.com/Java/Article/47817[/url] e considerando que ele usa a session para persistir os dados e eu uso o entitymanager fiz o seguinte:

1 - Quando o usuário se loga eu crio o atributo tenant na session assim:
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		session.setAttribute("tenant", "teste");
2 - Acrescentei no meu entity Agrupamento listado abaixo as anotações:
@FilterDef(name="tenantFilter", parameters=@ParamDef(name="tenant", type="string"))
@Filters(@Filter(name="tenantFilter", condition="tenant=:tenant"))
3 - Populei uma row da tabela com tenant = 'teste' 4 - Rodei a app e esperava que a query "from Agrupamento a" retornasse apenas a row correspondente ao tenant = "teste", porém retornou todas as rows da tabela. Na realidade estou engatinhando nesse negócio de multitenacy. Alguma dica? Abaixo o meu entity e o applicationContext onde configuro o entityManager. Obrigado, Marques
@javax.persistence.Entity
@Table(name = "agrupamento")
@FilterDef(name="tenantFilter", parameters=@ParamDef(name="tenant", type="string"))
@Filters(@Filter(name="tenantFilter", condition="tenant=:tenant"))
public class Agrupamento extends Entity {
	private static final long serialVersionUID = 1L;
	
	@Id 
	@GeneratedValue 
	private Long id;
	private String sigla;
	
	@Column(name="tabela", nullable=false)
	@Enumerated(EnumType.STRING)
	private AgrupamentoTabelaEnum tabela;
	
	@Column(name="tipo", nullable=false)
	@Enumerated(EnumType.STRING)
	private AgrupamentoEnum tipo;
	private String descricao;
	private String tenant;
	
	//getters and setters

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (!(obj instanceof Agrupamento))
			return false;
		Agrupamento other = (Agrupamento) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}	
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:faces="http://www.springframework.org/schema/faces"
	xmlns:int-security="http://www.springframework.org/schema/integration/security"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:sec="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/integration/security 
		http://www.springframework.org/schema/integration/security/spring-integration-security-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
		http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- resource security -->
	<!-- Note: Access-denied-page is invoked when user is AUTHENTICATED but 
		is not AUTHORIZED to access protected resources. When user is NOT AUTHENTICATED, 
		he is moved into form-login instead of access-denied-page. -->
	<sec:http auto-config="true">
		<sec:form-login login-page="/pages/public/login.jsf"
			authentication-failure-url="/pages/public/login.jsf?error=true" />
		<sec:logout logout-success-url="/pages/public/login.jsf" />
		<sec:intercept-url pattern="/index.jsf" access="ROLE_USER" />
		<sec:intercept-url pattern="/pages/app/**" access="ROLE_USER" />
		<sec:intercept-url pattern="/pages/admin/**" access="ROLE_USER" />
	</sec:http>

	<!-- business logic (method) security -->
	<sec:global-method-security
		secured-annotations="enabled" jsr250-annotations="enabled">
	</sec:global-method-security>

	<sec:authentication-manager alias="authenticationManager">
		<sec:authentication-provider>
			<sec:password-encoder hash="sha" />
			<sec:jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="SELECT username, password, enable FROM user WHERE username = ?"
				authorities-by-username-query="SELECT username, authority FROM user u INNER JOIN user_role r on u.id = r.idUser where username = ?" />
		</sec:authentication-provider>
	</sec:authentication-manager>

	<!-- Seta anotaçoes para serem usadas pelo Spring -->
	<context:annotation-config />

	<!-- Define o pacote onde o Spring vai procurar por beans anotados -->
	<context:component-scan base-package="br.com.fit.jpisnet" />

	<!-- define que as transaçoes irao ser anotadas -->
	<tx:annotation-driven />

	<!-- Configuracao do Banco de Dados -->
	<bean id="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpisnet" />
    		<property name="user" value="root" />
		<property name="password" value="segredo" />
		<property name="initialPoolSize" value="3" />
		<property name="minPoolSize" value="6" />
		<property name="maxPoolSize" value="20" />
		<property name="acquireIncrement" value="3" />
	</bean>

	<!-- Configuracao do Hibernate -->
	 
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="jpisnetPU" />
		<property name="dataSource" ref="dataSource" />
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
				<property name="showSql" value="true" />
			</bean>
		</property>
	</bean>
	
	<!-- Configuracao do gerente de transacoes do Spring -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	</bean>
	
	 <!-- View scope -->
    <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
        <property name="scopes">
            <map>
                <entry key="view">
                    <bean class="br.com.fit.jpisnet.resources.ViewScope"/>
                </entry>
            </map>
        </property>
    </bean>	
</beans>
Criado 14 de fevereiro de 2013
Respostas 0
Participantes 1