我能够直接使用hibernate来使用hibernate多租户,但我的要求是从jpa使用hibernate。 使用来自hibernate的Hibernate SessionFactory:
SessionFactory factory1=HibernateUtil.getSession();
Session session1=factory1.withOptions().tenantIdentifier("db2").openSession();
session1.beginTransaction();
使用JPA
EntityManagerFactory factory=JpaUtil.getEntityManagerFactory();
EntityManager em=factory.createEntityManager();
em.getTransaction().begin();
这样我就可以按照预期的方式跟踪EntityManager创建没有factory1.withOptions().tenantIdentifier("db2").openSession();
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.HibernateException: SessionFactory configured for multi-tenancy, but no tenant identifier specified
如何解决此错误?或者是否有其他方法可以在JPA中使用Hibernate Multi-tenancy?
我的persistence.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.nuc.jpa.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/db1" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root123" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.multiTenancy" value="SCHEMA" />
<property name="hibernate.multi_tenant_connection_provider" value="com.nuc.MultiTenantConnectionProvider" />
<property name="hibernate.tenant_identifier_resolver" value="com.nuc.MCurrentTenantIdentifierResolver"/>
</properties>
</persistence-unit>