下面列出了怎么用javax.persistence.EntityManagerFactory的API类实例代码及写法,或者点击链接到github查看源代码。
protected EntityManagerFactory newEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();
Interceptor interceptor = interceptor();
if (interceptor != null) {
configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}
Integrator integrator = integrator();
if (integrator != null) {
configuration.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(integrator));
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
);
return entityManagerFactoryBuilder.build();
}
public void migrate3() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("botlibre", properties);
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
try {
em.createNativeQuery("Update ChatChannel set creator_userid = (Select t2.admins_userid from CHAT_ADMINS t2 where t2.chatchannel_id = id)").executeUpdate();
em.createNativeQuery("Update Forum set creator_userid = (Select t2.admins_userid from forum_ADMINS t2 where t2.forum_id = id)").executeUpdate();
em.createNativeQuery("Update BotInstance set creator_userid = (Select t2.admins_userid from PANODRAINSTANCE_ADMINS t2 where t2.instances_id = id)").executeUpdate();
em.getTransaction().commit();
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
em.close();
factory.close();
}
}
@Override
public final void afterPropertiesSet() {
EntityManagerFactory emf = getEntityManagerFactory();
if (emf == null) {
throw new IllegalArgumentException("'entityManagerFactory' or 'persistenceUnitName' is required");
}
if (emf instanceof EntityManagerFactoryInfo) {
EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo) emf;
if (this.entityManagerInterface == null) {
this.entityManagerInterface = emfInfo.getEntityManagerInterface();
if (this.entityManagerInterface == null) {
this.entityManagerInterface = EntityManager.class;
}
}
}
else {
if (this.entityManagerInterface == null) {
this.entityManagerInterface = EntityManager.class;
}
}
this.shared = SharedEntityManagerCreator.createSharedEntityManager(
emf, getJpaPropertyMap(), this.synchronizedWithTransaction, this.entityManagerInterface);
}
@Bean
public EntityManagerFactory orderEntityManager() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order");
factory.setDataSource(orderDataSource());
Properties jpaProperties = new Properties();
//jpaProperties.put("hibernate.show_sql", "true");
//jpaProperties.put("hibernate.format_sql", "true");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect");
jpaProperties.put("hibernate.current_session_context_class", "jta");
jpaProperties.put("javax.persistence.transactionType", "jta");
jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup");
jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
factory.setJpaProperties(jpaProperties);
factory.afterPropertiesSet();
return factory.getObject();
}
private void throwDbException() throws SQLException
{
EntityManagerFactory emf = mock( EntityManagerFactory.class );
EntityManager em = mock( EntityManager.class );
EntityManager em1 = mock( EntityManager.class );
EntityTransaction transaction = mock( EntityTransaction.class );
when( transaction.isActive() ).thenReturn( false );
when( em.getTransaction() ).thenThrow( new PersistenceException() ).thenReturn( transaction );
when( emf.createEntityManager() ).thenReturn( em1 ).thenReturn( em );
try
{
monitorDao = new MonitorDataServiceExt( emf );
}
catch ( DaoException e )
{
e.printStackTrace();
}
}
/**
* Return a specified persistence unit for the given unit name,
* as defined through the "persistenceUnits" map.
* @param unitName the name of the persistence unit
* @return the corresponding EntityManagerFactory,
* or {@code null} if none found
* @see #setPersistenceUnits
*/
protected EntityManagerFactory getPersistenceUnit(String unitName) {
if (this.persistenceUnits != null) {
String unitNameForLookup = (unitName != null ? unitName : "");
if ("".equals(unitNameForLookup)) {
unitNameForLookup = this.defaultPersistenceUnitName;
}
String jndiName = this.persistenceUnits.get(unitNameForLookup);
if (jndiName == null && "".equals(unitNameForLookup) && this.persistenceUnits.size() == 1) {
jndiName = this.persistenceUnits.values().iterator().next();
}
if (jndiName != null) {
try {
return lookup(jndiName, EntityManagerFactory.class);
}
catch (Exception ex) {
throw new IllegalStateException("Could not obtain EntityManagerFactory [" + jndiName + "] from JNDI", ex);
}
}
}
return null;
}
private static void verifyHqlFetch(EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
try {
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.createQuery("from Person p left join fetch p.address a").getResultList();
transaction.commit();
} catch (Exception e) {
if (transaction.isActive()) {
transaction.rollback();
}
throw e;
}
} finally {
em.close();
}
}
@Override
public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(InjectionPoint injectionPoint) {
return new ResourceReferenceFactory<EntityManagerFactory>() {
@Override
public ResourceReference<EntityManagerFactory> createResource() {
if (persistenceUnitFactory == null) {
throw new IllegalStateException("Persistent unit factory not set, cannot resolve injection point: " + injectionPoint);
}
Object unit = persistenceUnitFactory.apply(injectionPoint);
if (unit == null || unit instanceof EntityManagerFactory) {
return new SimpleResourceReference<EntityManagerFactory>((EntityManagerFactory) unit);
}
throw new IllegalStateException("Not an EntityManagerFactory instance: " + unit);
}
};
}
/**
* Look up the EntityManagerFactory that this filter should use.
* <p>The default implementation looks for a bean with the specified name
* in Spring's root application context.
* @return the EntityManagerFactory to use
* @see #getEntityManagerFactoryBeanName
*/
protected EntityManagerFactory lookupEntityManagerFactory() {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
String emfBeanName = getEntityManagerFactoryBeanName();
String puName = getPersistenceUnitName();
if (StringUtils.hasLength(emfBeanName)) {
return wac.getBean(emfBeanName, EntityManagerFactory.class);
}
else if (!StringUtils.hasLength(puName) && wac.containsBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME)) {
return wac.getBean(DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME, EntityManagerFactory.class);
}
else {
// Includes fallback search for single EntityManagerFactory bean by type.
return EntityManagerFactoryUtils.findEntityManagerFactory(wac, puName);
}
}
private void buildFreshEntityManagerFactory() {
try {
Class ejb3ConfigurationClazz = loadClass("org.hibernate.ejb.Ejb3Configuration");
LOGGER.trace("new Ejb3Configuration()");
Object cfg = ejb3ConfigurationClazz.newInstance();
LOGGER.trace("cfg.configure( info, properties );");
if (info != null) {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{PersistenceUnitInfo.class, Map.class}, info, properties);
}
else {
ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "configure",
new Class[]{String.class, Map.class}, persistenceUnitName, properties);
}
LOGGER.trace("configured.buildEntityManagerFactory()");
currentInstance = (EntityManagerFactory) ReflectionHelper.invoke(cfg, ejb3ConfigurationClazz, "buildEntityManagerFactory",
new Class[]{});
} catch (Exception e) {
LOGGER.error("Unable to build fresh entity manager factory for persistence unit {}", persistenceUnitName);
}
}
@Test
public void testApplicationManagedEntityManagerWithoutTransaction() throws Exception {
Object testEntity = new Object();
EntityManager mockEm = mock(EntityManager.class);
given(mockEmf.createEntityManager()).willReturn(mockEm);
LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit();
EntityManagerFactory emf = cefb.getObject();
assertSame("EntityManagerFactory reference must be cached after init", emf, cefb.getObject());
assertNotSame("EMF must be proxied", mockEmf, emf);
EntityManager em = emf.createEntityManager();
assertFalse(em.contains(testEntity));
cefb.destroy();
verify(mockEmf).close();
}
public static EntityManagerFactory getEntityManagerFactory(final String pUnit) {
if (pUnit == null) {
return null;
}
if (emfMap == null) {
emfMap = new HashMap<String, EntityManagerFactory>();
}
if (emfMap.containsKey(pUnit)) {
return emfMap.get(pUnit);
} else {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(pUnit);
emfMap.put(pUnit, emf);
return emf;
}
}
@Bean
public EntityManagerFactory entityManagerFactory() {
// final Database database = Database.valueOf(vendor.toUpperCase());
final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setPersistenceUnitName("CCRI_PERSISTENCE_UNIT");
// factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("uk.nhs.careconnect.ri.database.entity");
factory.setDataSource(dataSource());
factory.setPersistenceProvider(new HibernatePersistenceProvider());
factory.setJpaProperties(jpaProperties());
factory.afterPropertiesSet();
return factory.getObject();
}
private static void updateItemDescriptions(final EntityManagerFactory emf, String[] newValues, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Item i1 = em.find(Item.class, 1L);
i1.setDescription(newValues[0]);
final Item i2 = em.find(Item.class, 2L);
i2.setDescription(newValues[1]);
final Item i3 = em.find(Item.class, 3L);
i3.setDescription(newValues[2]);
transaction.commit();
em.close();
assertRegionStats(expected, Item.class.getName(), stats);
}
/**<p>Executes the database migration for the provided JIRAs numbers.
* For example, for the https://issues.apache.org/jira/browse/IMAP-165 JIRA, simply invoke
* with IMAP165 as parameter.
* You can also invoke with many JIRA at once. They will be all serially executed.</p>
*
* TODO Extract the SQL in JAVA classes to XML file.
*
* @param jiras the JIRAs numbers
* @throws JpaMigrateException
*/
public static void main(String[] jiras) throws JpaMigrateException {
try {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("JamesMigrator");
EntityManager em = factory.createEntityManager();
for (String jira: jiras) {
JpaMigrateCommand jiraJpaMigratable = (JpaMigrateCommand) Class.forName(JPA_MIGRATION_COMMAND_PACKAGE + "." + jira.toUpperCase(Locale.US) + JpaMigrateCommand.class.getSimpleName()).newInstance();
LOGGER.info("Now executing {} migration", jira);
em.getTransaction().begin();
jiraJpaMigratable.migrate(em);
em.getTransaction().commit();
LOGGER.info("{} migration is successfully achieved", jira);
}
} catch (Throwable t) {
throw new JpaMigrateException(t);
}
}
/**
* Constructor used on server side.
*/
private JpaModule(EntityManagerFactory emFactory, EntityManager em, TransactionRunner transactionRunner) {
this();
this.emFactory = emFactory;
this.em = em;
this.transactionRunner = transactionRunner;
setQueryFactory(JpaCriteriaQueryFactory.newInstance());
if (emFactory != null) {
Set<ManagedType<?>> managedTypes = emFactory.getMetamodel().getManagedTypes();
for (ManagedType<?> managedType : managedTypes) {
Class<?> managedJavaType = managedType.getJavaType();
MetaElement meta = jpaMetaLookup.getMeta(managedJavaType, MetaJpaDataObject.class);
if (meta instanceof MetaEntity) {
addRepository(JpaRepositoryConfig.builder(managedJavaType).build());
}
}
}
this.setRepositoryFactory(new DefaultJpaRepositoryFactory());
}
public static TransactionType getEntityManagerFactoryTransactionType(EntityManagerFactory emf) {
EntityManager manager = emf.createEntityManager();
// Hibernate does not throw exception when getTransaction() in JTA context is called, this is the workaround
// for JTA detection
if (emf.getProperties().containsKey("hibernate.transaction.coordinator_class") &&
emf.getProperties().get("hibernate.transaction.coordinator_class") instanceof Class &&
((Class) emf.getProperties().get("hibernate.transaction.coordinator_class")).getSimpleName()
.equals("JtaTransactionCoordinatorBuilderImpl")) {
return TransactionType.JTA;
}
try {
manager.getTransaction();
return TransactionType.RESOURCE_LOCAL;
} catch (IllegalStateException e) {
manager.close();
return TransactionType.JTA;
}
}
public EntityManagerFactory getEntityManagerFactory(String unitName)
throws Exception {
final ITestDB testDb = TestDataSources.get(unitName, runOnProductiveDB);
if (!initializedDBs.contains(testDb) && !runOnProductiveDB) {
testDb.initialize();
initializedDBs.add(testDb);
}
EntityManagerFactory f = factoryCache.get(unitName);
if (f == null) {
f = buildEntityManagerFactory(testDb, unitName);
factoryCache.put(unitName, f);
}
return f;
}
private static void storeTestPersons(final EntityManagerFactory emf, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.persist(new Person("Gizmo"));
em.persist(new Person("Quarkus"));
em.persist(new Person("Hibernate ORM"));
em.persist(new Person("Infinispan"));
transaction.commit();
em.close();
assertRegionStats(expected, Person.class.getName(), stats);
}
@PersistenceUnit
public void setEmf(EntityManagerFactory emf) {
if (this.emf != null) {
throw new IllegalStateException("Already called");
}
this.emf = emf;
}
public void lookupPersistenceUnit() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("java:comp/env/persistence/TestUnit");
Assert.assertNotNull("The EntityManagerFactory is null", emf);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
@Test
public void testMapping() throws Exception {
// Hibernate configuration
Map<String, String> hibernateProperties = new HashMap<String, String>();
hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyTenSevenDialect");
hibernateProperties.put("hibernate.connection.driver_class", "org.apache.derby.jdbc.EmbeddedDriver");
hibernateProperties.put("hibernate.connection.url", "jdbc:derby:target/test-database/database;create=true");
hibernateProperties.put("hibernate.hbm2ddl.auto", "create");
// initialise Hibernate
EntityManagerFactory emf = createEntityManagerFactory(hibernateProperties);//, hibernateProperties);
EntityManager em = emf.createEntityManager();
// deserialize test XML document
JobStream jaxbElement = (JobStream) JAXBContextUtils.unmarshal("org.jvnet.hyperjaxb3.ejb.tests.componentjpa2.tests", readFileAsString("src/test/resources/tests.xml"));
//JobStream mails = (JobStream) JAXBElementUtils.getValue(jaxbElement);
// persist object
em.getTransaction().begin();
em.persist(jaxbElement);
em.getTransaction().commit();
// retrieve persisted object
JobStream persistedMails = em.find(JobStream.class,1L);
System.out.println("persistedObjects = " + persistedMails);
em.close();
emf.close();
}
@Override
public ODataJPAContext initializeODataJPAContext()
throws ODataJPARuntimeException {
ODataJPAContext oDataJPAContext = this.getODataJPAContext();
try {
EntityManagerFactory emf = JpaEntityManagerFactory
.getEntityManagerFactory();
oDataJPAContext.setEntityManagerFactory(emf);
oDataJPAContext.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
return oDataJPAContext;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public SharedEntityManagerInvocationHandler(
EntityManagerFactory target, @Nullable Map<?, ?> properties, boolean synchronizedWithTransaction) {
this.targetFactory = target;
this.properties = properties;
this.synchronizedWithTransaction = synchronizedWithTransaction;
initProxyClassLoader();
}
@Override
public void preHandle(WebRequest request) throws DataAccessException {
String key = getParticipateAttributeName();
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
return;
}
EntityManagerFactory emf = obtainEntityManagerFactory();
if (TransactionSynchronizationManager.hasResource(emf)) {
// Do not modify the EntityManager: just mark the request accordingly.
Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
int newCount = (count != null ? count + 1 : 1);
request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
}
else {
logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
try {
EntityManager em = createEntityManager();
EntityManagerHolder emHolder = new EntityManagerHolder(em);
TransactionSynchronizationManager.bindResource(emf, emHolder);
AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
asyncManager.registerCallableInterceptor(key, interceptor);
asyncManager.registerDeferredResultInterceptor(key, interceptor);
}
catch (PersistenceException ex) {
throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
}
}
}
private static void testQuery(EntityManagerFactory entityManagerFactory) {
//Load all persons and run some checks on the query results:
Map<String, Counts> counts = new TreeMap<>();
counts.put(Person.class.getName(), new Counts(4, 0, 0, 4));
counts.put(RegionFactory.DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, new Counts(1, 0, 1, 1));
verifyListOfExistingPersons(entityManagerFactory, counts);
//Load all persons with same query and verify query results
counts = new TreeMap<>();
counts.put(Person.class.getName(), new Counts(0, 4, 0, 4));
counts.put(RegionFactory.DEFAULT_QUERY_RESULTS_REGION_UNQUALIFIED_NAME, new Counts(0, 1, 0, 1));
verifyListOfExistingPersons(entityManagerFactory, counts);
}
@Test
public void testSequences_AnnotationAtMethodLevel() throws Exception {
EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
assertNotNull(factory);
TestEntity3 testEntity1 = new TestEntity3();
testEntity1.setName("MyAwesomeTestEntity1");
// number in this case is generated from a sequence
assertNull(testEntity1.getNumber());
EntityManager entityManager = factory.createEntityManager();
try {
entityManager.persist(testEntity1);
assertNotNull(testEntity1.getNumber());
} finally {
entityManager.close();
}
TestEntity3 testEntity2 = new TestEntity3();
testEntity2.setName("MyAwesomeTestEntity2");
assertNull(testEntity2.getNumber());
entityManager = factory.createEntityManager();
try {
// try merge here and make sure it works with that as well
testEntity2 = entityManager.merge(testEntity2);
assertNotNull(testEntity2.getNumber());
assertEquals(Integer.valueOf(Integer.valueOf(testEntity1.getNumber()).intValue() + 1), Integer.valueOf(
testEntity2.getNumber()));
} finally {
entityManager.close();
}
}
@Sessional
@Override
public void init() {
for (EntityType<?> entityType: ((EntityManagerFactory)persistManager.getSessionFactory()).getMetamodel().getEntities()) {
Class<?> entityClass = entityType.getJavaType();
nextIds.put(entityClass, new AtomicLong(getMaxId(entityClass)+1));
}
}
/**
* {@inheritDoc}
* <p/>
* Note: per-spec, the values passed as {@code properties} override values found in {@link PersistenceUnitInfo}
*/
@Override
public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) {
log.tracef( "Starting createContainerEntityManagerFactory : %s", info.getPersistenceUnitName() );
return getEntityManagerFactoryBuilder( info, properties ).build();
}
private Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> createEntityManagers(final BeanContext beanContext) {
// create the extended entity managers
final Index<EntityManagerFactory, BeanContext.EntityManagerConfiguration> factories = beanContext.getExtendedEntityManagerFactories();
Index<EntityManagerFactory, JtaEntityManagerRegistry.EntityManagerTracker> entityManagers = null;
if (factories != null && factories.size() > 0) {
entityManagers = new Index<>(new ArrayList<>(factories.keySet()));
for (final Map.Entry<EntityManagerFactory, BeanContext.EntityManagerConfiguration> entry : factories.entrySet()) {
final EntityManagerFactory entityManagerFactory = entry.getKey();
JtaEntityManagerRegistry.EntityManagerTracker entityManagerTracker = entityManagerRegistry.getInheritedEntityManager(entityManagerFactory);
final EntityManager entityManager;
if (entityManagerTracker == null) {
final Map properties = entry.getValue().getProperties();
final SynchronizationType synchronizationType = entry.getValue().getSynchronizationType();
if (synchronizationType != null) {
if (properties != null) {
entityManager = entityManagerFactory.createEntityManager(synchronizationType, properties);
} else {
entityManager = entityManagerFactory.createEntityManager(synchronizationType);
}
} else if (properties != null) {
entityManager = entityManagerFactory.createEntityManager(properties);
} else {
entityManager = entityManagerFactory.createEntityManager();
}
entityManagerTracker = new JtaEntityManagerRegistry.EntityManagerTracker(entityManager, synchronizationType != SynchronizationType.UNSYNCHRONIZED);
} else {
entityManagerTracker.incCounter();
}
entityManagers.put(entityManagerFactory, entityManagerTracker);
}
}
return entityManagers;
}