public static void main(String[] args) { EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("pl.edu.bogdan.training.db.entity"); EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> from = cq.from(User.class); Join<User, Role> join = from.join("role", JoinType.LEFT); cq.where(cb.equal(join.get("name"), "ordinary")); TypedQuery<User> tq = em.createQuery(cq); List<User> users = tq.getResultList(); for (User u : users) { System.out.println(u.getLastName()); } em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }
@Test public void jpa() { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpa"); Employee employee = new Employee(); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(employee); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close(); assertNotNull(employee.id); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(8, finishedSpans.size()); checkSpans(finishedSpans); assertNull(mockTracer.activeSpan()); }
@Test public void jpaWithActiveSpanOnlyNoParent() { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpa_active_span_only"); Employee employee = new Employee(); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(employee); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close(); assertNotNull(employee.id); List<MockSpan> finishedSpans = mockTracer.finishedSpans(); assertEquals(0, finishedSpans.size()); assertNull(mockTracer.scopeManager().active()); }
private synchronized EntityManager getEntityManager(final PersistenceUnitInfo unit) { if (entityManagers.containsKey(unit.getPersistenceUnitName())) { return entityManagers.get(unit.getPersistenceUnitName()); } final String providerClassName = unit.getPersistenceProviderClassName(); try { final PersistenceProvider provider = (PersistenceProvider) Class.forName(providerClassName).newInstance(); final EntityManagerFactory emf = provider.createContainerEntityManagerFactory(unit, new HashMap()); final EntityManager entityManager = emf.createEntityManager(); entityManagers.put(unit.getPersistenceUnitName(), entityManager); entityManager.getTransaction().begin(); return entityManager; } catch (final IllegalAccessException | InstantiationException | ClassNotFoundException e) { throw new TestEEfiException("Failed to load persistence provider class " + providerClassName, e); } }
/** * Opens an {@link EntityManagerFactory} for the provided {@code persistenceUnit} if not already opened/cached. * * @param persistenceUnit The name of the persistence unit * @return The {@link EntityManagerFactory} for {@code persistenceUnit} */ private static synchronized EntityManagerFactory getEntityManagerFactory(String persistenceUnit) { if (persistenceUnit.isEmpty() && DEFAULT_PERSISTENCE_UNIT != null) { persistenceUnit = DEFAULT_PERSISTENCE_UNIT; } if (!SESSION_FACTORY_STORE.containsKey(persistenceUnit)) { LOG.debug("Create new EntityManagerFactory for persistence unit {}", persistenceUnit); SESSION_FACTORY_STORE.put( persistenceUnit, Persistence.createEntityManagerFactory( persistenceUnit.isEmpty() ? null : persistenceUnit, PERSISTENCE_PROPERTIES.get(persistenceUnit) ) ); } return SESSION_FACTORY_STORE.get(persistenceUnit); }
/** * @param unitName persistence unit name * @param properties nullable properties for overriding * @return created TransactionProvider */ public static TransactionProvider setupFactory(String unitName, Map<String, String> properties) { if (!providers.containsKey(unitName)) { synchronized (HibernateUtils.class) { if (!providers.containsKey(unitName)) { // Setup Factory & Provider EntityManagerFactory factory = Persistence.createEntityManagerFactory(unitName, properties); TransactionProvider provider = new TransactionProvider(factory); // Put to Map providers.put(unitName, provider); return provider; } } } throw new RuntimeException(new IllegalStateException("Factory already initialized.")); }
@Bean public EntityManagerFactory entityManagerFactory() throws SQLException { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.setGenerateDdl(true); // Crea la tabella e le colonne quando non esistono vendorAdapter.setShowSql(config.getShowSql()); vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(vendorAdapter); List<String> packages = config.getDbEntityPackages(); packages.add("net.yadaframework.persistence.entity"); packages.add("net.yadaframework.security.persistence.entity"); packages.add("net.yadaframework.cms.persistence.entity"); packages.add("net.yadaframework.commerce.persistence.entity"); log.info("Scanning packages for entities: {}", StringUtils.join(packages, ",")); factory.setPackagesToScan(packages.toArray(new String[]{})); factory.setDataSource(dataSource()); factory.afterPropertiesSet(); return factory.getObject(); }
private void btn_kabuletActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_kabuletActionPerformed // TODO add your handling code here: if (tbl_arkadaslistesi.getSelectedRow() < 0) { JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz"); return; } int id = (int) dtm2.getValueAt(tbl_arkadaslistesi.getSelectedRow(), 0); EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("UPDATE ARKADASLIK u SET u.kabulDurumu=true WHERE u.idUserKabul=:kabulid AND U.idUserIstek=:istekid"); q.setParameter("istekid", id); q.setParameter("kabulid", Frm_Login.loginuser.getId()); em.getTransaction().begin(); q.executeUpdate(); em.getTransaction().commit(); }
private void btn_silActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_silActionPerformed // TODO add your handling code here: if (tbl_arkadaslistesi.getSelectedRow() < 0) { JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz"); return; } int id = (int) dtm2.getValueAt(tbl_arkadaslistesi.getSelectedRow(), 0); EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("DELETE FROM ARKADASLIK u WHERE u.idUserKabul=:kabulid AND U.idUserIstek=:istekid"); q.setParameter("istekid", id); q.setParameter("kabulid", Frm_Login.loginuser.getId()); em.getTransaction().begin(); q.executeUpdate(); em.getTransaction().commit(); }
@Test public void testPersistence() { // Make sure derby.log is in target System.setProperty("derby.stream.error.file", "target/derby.log"); TaskServiceImpl taskServiceImpl = new TaskServiceImpl(); EntityManagerFactory emf = createTestEMF(); final EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); taskServiceImpl.em = em; TaskService taskService = taskServiceImpl; Task task = new Task(); task.setId(1); task.setTitle("test"); taskService.addTask(task); Task task2 = taskService.getTask(1); Assert.assertEquals(task.getTitle(), task2.getTitle()); em.getTransaction().commit(); em.close(); }
@Test public void jpa_with_parent() { try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpa"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(new Employee()); entityManager.persist(new Employee()); entityManager.getTransaction().commit(); entityManager.close(); entityManagerFactory.close(); } List<MockSpan> spans = mockTracer.finishedSpans(); assertEquals(11, spans.size()); checkSameTrace(spans); assertNull(mockTracer.activeSpan()); }
@Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) { // Register JPA Datastore (transactional) if (beanFactory instanceof ListableBeanFactory) { String[] emfBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( (ListableBeanFactory) beanFactory, EntityManagerFactory.class, true, false); if (emfBeanNames == null || emfBeanNames.length == 0) { emfBeanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors((ListableBeanFactory) beanFactory, AbstractEntityManagerFactoryBean.class, true, false); } if (emfBeanNames != null && emfBeanNames.length == 1) { String emfBeanName = (emfBeanNames[0].startsWith("&")) ? emfBeanNames[0].substring(1) : emfBeanNames[0]; JpaDatastoreRegistrar.registerDatastore(registry, null, PrimaryMode.AUTO, emfBeanName, true, false, beanClassLoader); } } }
private void btn_degistirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_degistirActionPerformed // TODO add your handling code here: // UPDATE EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("UPDATE Hasta h SET h.adi=:ad,h.soyadi=:soyad, h.idDoktor=:did WHERE h.id=:id"); q.setParameter("ad", txt_hastaadi.getText()); q.setParameter("soyad", txt_hastasoyadi.getText()); q.setParameter("did", doktorlar.get(cmb_doktorlar.getSelectedIndex()).getId()); q.setParameter("id", tbl_hastalar.getValueAt(tbl_hastalar.getSelectedRow(), 0)); em.getTransaction().begin(); q.executeUpdate(); em.getTransaction().commit(); /// dtm.setRowCount(0); q = em.createQuery("SELECT h FROM Hasta h"); List<Hasta> hastalar = q.getResultList(); for (Hasta hs : hastalar) { dtm.addRow(new Object[]{hs.getId(), hs.getAdi(), hs.getSoyadi(), hs.getIdDoktor()}); } tbl_hastalar.setModel(dtm); }
@Test public void lifeCycleTest() { EntityManagerFactory emf = mockEmf(); Coordinator coordinator = new DummyCoordinator(); EMSupplierImpl emSupplier = new EMSupplierImpl("myunit", emf, coordinator); assertIllegalState(emSupplier); coordinator.begin("test", 0); EntityManager em = emSupplier.get(); Assert.assertNotNull("EM should be present after preCall", em); coordinator.begin("testinner", 0); Assert.assertSame("Same EM for inner preCall", em, emSupplier.get()); coordinator.pop().end(); Assert.assertSame("EM must still be the same after inner postCall", em, emSupplier.get()); coordinator.pop().end(); assertIllegalState(emSupplier); boolean clean = emSupplier.close(); Assert.assertTrue("Shutdown should be clean", clean); }
@Test public void asyncCleanLifeCycleTest() throws InterruptedException { EntityManagerFactory emf = mockEmf(); final Coordinator coordinator = new DummyCoordinator(); final EMSupplierImpl emSupplier = new EMSupplierImpl("myunit", emf,coordinator); final Semaphore preCallSem = new Semaphore(0); Runnable command = new Runnable() { @Override public void run() { coordinator.begin("test", 0); preCallSem.release(); coordinator.pop().end(); } }; Executors.newSingleThreadExecutor().execute(command); preCallSem.acquire(); // EMs not closed when close is called but are closed before timeout boolean clean = emSupplier.close(); Assert.assertTrue("Shutdown should be clean", clean); }
/** * 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); } }
@Test public void testCarEMFBuilderExternalDS() throws Exception { DataSourceFactory dsf = getService(DataSourceFactory.class, "(" + OSGI_JDBC_DRIVER_CLASS + "=org.apache.derby.jdbc.EmbeddedDriver)"); EntityManagerFactoryBuilder emfBuilder = getService(EntityManagerFactoryBuilder.class, "(osgi.unit.name=" + EXTERNAL_TEST_UNIT + ")"); assertEquals(getProviderClassName(), emfBuilder.getPersistenceProviderName()); assertEquals(getProviderBundle(), emfBuilder.getPersistenceProviderBundle()); Properties jdbcProps = new Properties(); jdbcProps.setProperty("url", "jdbc:derby:memory:DSFTEST;create=true"); Map<String, Object> props = new HashMap<String, Object>(); props.put("javax.persistence.nonJtaDataSource", dsf.createDataSource(jdbcProps)); props.put("javax.persistence.transactionType", RESOURCE_LOCAL.name()); EntityManagerFactory emf = emfBuilder.createEntityManagerFactory(props); carLifecycleRL(emf.createEntityManager()); }
/** * This method looks for a matching EntityManagerFactoryBuilder service to create the * EMF with. */ @Override public EntityManagerFactory createEntityManagerFactory(String emName, @SuppressWarnings("rawtypes") Map map) { for (Entry<ServiceReference<Object>, Object> e : tracker.getTracked().entrySet()) { String serviceUnitName = String.valueOf(e.getKey().getProperty("osgi.unit.name")); if(serviceUnitName.equals(emName)) { try { Object emfBuilder = e.getValue(); Method m = emfBuilder.getClass().getMethod("createEntityManagerFactory", Map.class); return (EntityManagerFactory) m.invoke(emfBuilder, map); } catch (Exception ex) { throw new PersistenceException("Failed to create an EntityManagerFactory for unit " + emName, ex); } } } return null; }
@Test public void testQuiz(){ Quiz quiz = new Quiz(); quiz.setQuestion("Will this test pass?"); quiz.setFirstAnswer("Yes"); quiz.setSecondAnswer("No"); quiz.setThirdAnswer("Maybe"); quiz.setFourthAnswer("No idea"); quiz.setIndexOfCorrectAnswer(0); EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB"); EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(quiz); tx.commit(); }
/** * retrieves the list of user emails registered. * * @return users the list of user emails * */ public static List<String> listUsers() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData"); EntityManager em = emf.createEntityManager(); Query query = em.createQuery("SELECT username FROM User"); @SuppressWarnings("unchecked") List<String> users = query.getResultList(); em.close(); return users; }
@Override public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(InjectionPoint injectionPoint) { return new ResourceReferenceFactory<EntityManagerFactory>() { @Override public ResourceReference<EntityManagerFactory> createResource() { return new SimpleResourceReference<EntityManagerFactory>(resolvePersistenceUnit(injectionPoint)); } }; }
@Bean public EntityManagerFactory entityManagerFactory(JpaVendorAdapter jpaVendorAdapter, DataSource dataSource) { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setJpaVendorAdapter(jpaVendorAdapter); factory.setPackagesToScan("hello.entities"); factory.setDataSource(dataSource); factory.afterPropertiesSet(); return factory.getObject(); }
public DefaultJpaResolutionContext(EntityManagerFactory entityManagerFactory, ORMPlatform platform, ExpressionResolverHandler expressionResolverHandler, AliasMode aliasMode) { super(null, 0, aliasMode); ObjectUtils.argumentNotNull(entityManagerFactory, "EntityManagerFactory must be not null"); ObjectUtils.argumentNotNull(expressionResolverHandler, "ExpressionResolverHandler must be not null"); this.entityManagerFactory = entityManagerFactory; this.platform = platform; this.expressionResolverHandler = expressionResolverHandler; }
@Bean @Autowired public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(emf); return txManager; }
private void btn_sorgulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_sorgulaActionPerformed // TODO add your handling code here: EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); dtm.setRowCount(0); Query q = em.createQuery("SELECT h FROM Hasta h WHERE h.idDoktor=:did"); q.setParameter("did", doktorlar.get(cmb_doktorlar.getSelectedIndex()).getId()); List<Hasta> hastalar = q.getResultList(); for (Hasta hs : hastalar) { dtm.addRow(new Object[]{hs.getId(), hs.getAdi(), hs.getSoyadi(), hs.getIdDoktor()}); } tbl_hastalar.setModel(dtm); }
public HibernateDBCreator(EntityManagerFactory entityManagerFactory) { if (entityManagerFactory == null) { throw new IllegalArgumentException(); } this.entityManagerFactory = entityManagerFactory; }
@Bean public JpaDatastore datastore(EntityManagerFactory emf) throws Exception { return JpaDatastore.builder().entityManagerFactory(emf) // use spring shared entitymanager to join spring transactions .entityManagerInitializer(f -> SharedEntityManagerCreator.createSharedEntityManager(f)) .autoFlush(true).traceEnabled(true).withExpressionResolver(KeyIs.RESOLVER).build(); }
@Bean public JpaDatastore datastore(EntityManagerFactory emf) throws Exception { return JpaDatastore.builder().entityManagerFactory(emf) // use spring shared entitymanager to join spring transactions .entityManagerInitializer(f -> SharedEntityManagerCreator.createSharedEntityManager(f)) .autoFlush(true).withExpressionResolver(KeyIs.RESOLVER) .withExpressionResolver(new UselessResolver()).traceEnabled(true).build(); }
@Bean public FactoryBean<EntityManagerFactory> entityManagerFactory() { LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); emf.setDataSource(dataSource()); emf.setJpaVendorAdapter(new EclipseLinkJpaVendorAdapter()); emf.setPackagesToScan(TestJpaDomain.class.getPackage().getName()); emf.setPersistenceUnitName("test"); emf.getJpaPropertyMap().put("eclipselink.weaving", "false"); return emf; }
/** * Exposes all entities as repositories. */ public void exposeAllEntities(EntityManagerFactory emf) { Set<ManagedType<?>> managedTypes = emf.getMetamodel().getManagedTypes(); for (ManagedType<?> managedType : managedTypes) { Class<?> managedJavaType = managedType.getJavaType(); if (managedJavaType.getAnnotation(Entity.class) != null) { addRepository(JpaRepositoryConfig.builder(managedJavaType).build()); } } }
/** * Initializes and returns singleton EntityManagerFactory. * * @return singleton EntityManagerFactory. */ public static EntityManagerFactory getEntityManagerFactory() { if (EntityManagerFactoryProvider.entityManagerFactory == null || !EntityManagerFactoryProvider.entityManagerFactory.isOpen()) { synchronized (EntityManagerFactoryProvider.class) { if (EntityManagerFactoryProvider.entityManagerFactory == null || !EntityManagerFactoryProvider.entityManagerFactory.isOpen()) { initEntityManagerFactory(DataSourceProvider.getInstance().getDataSource()); } } } return EntityManagerFactoryProvider.entityManagerFactory; }
@Test public void testCloseEntityManagerFactoryException() throws Exception { final EntityManagerFactory emf = mock(EntityManagerFactory.class); doThrow(new RuntimeException("Boom")).when(emf).close(); LiquibaseHelper.closeQuietly(emf); verify(emf).close(); }
public JPAConnection() { if (entityManager == null) { EntityManagerFactory emf; if (DB.equals(DERBY)) { emf = Persistence.createEntityManagerFactory(DERBY); } else { Map<String, String> propertyMap = new HashMap<>(); propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0); emf = Persistence.createEntityManagerFactory(CASSANDRA, propertyMap); } entityManager = emf.createEntityManager(); } }
/** * retrieves the list of <code>UserRole</code>-objects by its email. * * @param email * the email * @return userRoles the roles * */ public static List<UserRole> getUserRolesByEmail(String username) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData"); EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<UserRole> q = cb.createQuery(UserRole.class); Root<UserRole> c = q.from(UserRole.class); q.select(c).where(cb.equal(c.get("username"), username)); TypedQuery<UserRole> query = em.createQuery(q); List<UserRole> roles = query.getResultList(); em.close(); return roles; }
private EntityManager resolveEntityManager(String requestingBeanName) { // Obtain EntityManager reference from JNDI? EntityManager em = getPersistenceContext(this.unitName, false); if (em == null) { // No pre-built EntityManager found -> build one based on factory. // Obtain EntityManagerFactory from JNDI? EntityManagerFactory emf = getPersistenceUnit(this.unitName); if (emf == null) { // Need to search for EntityManagerFactory beans. emf = findEntityManagerFactory(this.unitName, requestingBeanName); } // Inject a shared transactional EntityManager proxy. if (emf instanceof EntityManagerFactoryInfo && ((EntityManagerFactoryInfo) emf).getEntityManagerInterface() != null) { // Create EntityManager based on the info's vendor-specific type // (which might be more specific than the field's type). em = SharedEntityManagerCreator.createSharedEntityManager( emf, this.properties, this.synchronizedWithTransaction); } else { // Create EntityManager based on the field's type. em = SharedEntityManagerCreator.createSharedEntityManager( emf, this.properties, this.synchronizedWithTransaction, getResourceType()); } } return em; }
private EntityManagerFactory buildEntityManagerFactory(ITestDB testDb, String unitName) throws Exception { Map<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Environment.HBM2DDL_AUTO, ""); properties.put(Environment.DATASOURCE, createManagedDataSource(testDb .getDataSource())); properties.put("hibernate.search.autoregister_listeners", System.getProperty("hibernate.search.autoregister_listeners")); properties.put("hibernate.transaction.jta.platform", "org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"); properties.put("hibernate.id.new_generator_mappings", "false"); properties.put("org.hibernate.SQL", "false"); EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(unitName, properties); sf = ((EntityManagerFactoryImpl) entityManagerFactory).getSessionFactory(); return entityManagerFactory; }
@Override public Future<EntityManagerFactory> getEntityManagerFactory(String datasourceName) { Properties properties = createProperties(); PersistenceProvider provider = new HibernatePersistenceProvider(); SmartPersistanceUnitInfo persistenceUnitInfo = new DefaultPersistenceUnitInfoImpl(datasourceName); persistenceUnitInfo.setProperties(properties); // Using RESOURCE_LOCAL for manage transactions on DAO side. persistenceUnitInfo.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL); Map<Object, Object> configuration = new HashMap<>(); properties.entrySet().stream().forEach(e -> configuration.put(e.getKey(), e.getValue())); synchronized (vertx) { Future<EntityManagerFactory> future = Future.future(); vertx.executeBlocking(f1 -> { config.getJsonArray("annotated_classes", new JsonArray()).stream() .forEach(p -> scanAnnotatedClasses(p.toString(), persistenceUnitInfo)); EntityManagerFactory emf = provider.createContainerEntityManagerFactory(persistenceUnitInfo, configuration); future.complete(emf); }, future.completer()); return future; } }
@Override public List<Book> getBooksOfAuthorWithId(int id) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity"); EntityManager em = entityManagerFactory.createEntityManager(); // begining of transaction em.getTransaction().begin(); Author author = em.find(Author.class, id); System.out.println(author.toString()); for (Book b : author.getBooks()) { System.out.println(b.toString()); } return author == null ? new ArrayList<Book>() : author.getBooks(); }
/** * Prepare a transaction on the given EntityManager, if possible. * @param em the EntityManager to prepare * @param emf the EntityManagerFactory that the EntityManager has been created with * @return an arbitrary object that holds transaction data, if any * (to be passed into cleanupTransaction) * @see JpaDialect#prepareTransaction */ private static Object prepareTransaction(EntityManager em, EntityManagerFactory emf) { if (emf instanceof EntityManagerFactoryInfo) { EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo) emf; JpaDialect jpaDialect = emfInfo.getJpaDialect(); if (jpaDialect != null) { return jpaDialect.prepareTransaction(em, TransactionSynchronizationManager.isCurrentTransactionReadOnly(), TransactionSynchronizationManager.getCurrentTransactionName()); } } return null; }
@Test public void selectSqlNativoTest() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start"); EntityManager manager = factory.createEntityManager(); Query query = manager.createNativeQuery("Select * from cidade c"); List<Cidade> cidades = query.getResultList(); factory.close(); }