javax.persistence.Persistence Java Examples
The following examples show how to use
javax.persistence.Persistence.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Migrate.java From BotLibre with Eclipse Public License 1.0 | 6 votes |
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(); } }
Example #2
Source File: EjbqlApp.java From jasperreports with GNU Lesser General Public License v3.0 | 6 votes |
/** * */ public void fill() throws JRException { long start = System.currentTimeMillis(); // create entity manager factory for connection with database EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu1", new HashMap<Object, Object>()); EntityManager em = emf.createEntityManager(); try { Map<String, Object> parameters = getParameters(em); JasperFillManager.fillReportToFile("build/reports/JRMDbReport.jasper", parameters); em.close(); System.err.println("Filling time : " + (System.currentTimeMillis() - start)); } finally { if (em.isOpen()) em.close(); if (emf.isOpen()) emf.close(); } }
Example #3
Source File: DeleteIT.java From bookapp-cqrs with Apache License 2.0 | 6 votes |
@Test public void test() { EntityManager em = Persistence.createEntityManagerFactory( "ch.bfh.swos.bookapp.book.domain").createEntityManager(); Query q = em.createQuery("select a from Author a"); @SuppressWarnings("unchecked") List<Author> foundAuthors = q.getResultList(); Author firstAuthor = foundAuthors.get(0); // Write access needs a transaction em.getTransaction().begin(); em.remove(firstAuthor); em.getTransaction().commit(); }
Example #4
Source File: JpaDb.java From crushpaper with GNU Affero General Public License v3.0 | 6 votes |
/** * Create a JPA entity manager factory which is used to create entity * managers which are used to query and commit to the DB. */ private synchronized void buildEntityManagerFactory() { if (entityManagerFactory != null) { return; } registerShutdownHook(this); Map<String, Object> configOverrides = new HashMap<String, Object>(); String dbPath = dbDirectory.getAbsolutePath(); configOverrides.put("hibernate.search.default.indexBase", dbPath); configOverrides.put("hibernate.connection.url", "jdbc:h2:" + dbPath + File.separator + "db" + // Make sure that transactions are fully isolated. ";LOCK_MODE=1" + // Make sure the database is not closed if all of the entity // managers are closed. ";DB_CLOSE_DELAY=-1"); // This string has to match what is in persistence.xml. entityManagerFactory = Persistence.createEntityManagerFactory( "manager", configOverrides); }
Example #5
Source File: UpdateIT.java From bookapp-cqrs with Apache License 2.0 | 6 votes |
@Test public void test() { EntityManager em = Persistence.createEntityManagerFactory( "ch.bfh.swos.bookapp.book.domain").createEntityManager(); Query q = em.createQuery("select a from Author a"); @SuppressWarnings("unchecked") List<Author> foundAuthors = q.getResultList(); Author firstAuthor = foundAuthors.get(0); // Write access needs a transaction em.getTransaction().begin(); firstAuthor.setLastname("OtherName"); em.getTransaction().commit(); // Entity is persisted automatically after commit because it is managed // by jpa. @SuppressWarnings("unchecked") List<Author> updatedAuthors = q.getResultList(); Author updatedAuthor = updatedAuthors.get(0); Assert.assertTrue(updatedAuthor.getLastname().equals("OtherName")); }
Example #6
Source File: IdHandlingTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testPersistTwiceInNewFactory() { User02 user02 = new User02(); user02.setId(1L); boolean persisted = persistInATransaction(user02); assertTrue(persisted); em.close(); factory.close(); factory = Persistence.createEntityManagerFactory("DB"); em = factory.createEntityManager(); persisted = persistInATransaction(user02); assertTrue(persisted); /* Here we managed to commit, because createEntityManagerFactory does create a new database, as we used "create-drop" in the persisten.xml file */ }
Example #7
Source File: InfoBean.java From tomee with Apache License 2.0 | 6 votes |
@PostConstruct protected void showWelcomeMessage() { String versionString = ClassUtils.getJarVersion(InfoBean.class); if (versionString != null) { this.applicationMessageVersionInfo = " (v" + versionString + ")"; } this.beanValidationVersion = ClassUtils.getJarVersion(Validation.buildDefaultValidatorFactory().getValidator().getClass()); this.jpaVersion = ClassUtils.getJarVersion(Persistence.createEntityManagerFactory("demoApplicationPU").getClass()); if (!ProjectStage.IntegrationTest.equals(this.projectStage)) { this.messageContext.message().text("{msgWelcome}").add(); } }
Example #8
Source File: JAXBAndJPATest.java From hyperjaxb3 with BSD 2-Clause "Simplified" License | 6 votes |
public void setUp() throws Exception { objectFactory = new ObjectFactory(); final Properties persistenceProperties = new Properties(); InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream( "persistence.properties"); persistenceProperties.load(is); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { } } } entityManagerFactory = Persistence.createEntityManagerFactory( "generated", persistenceProperties); context = JAXBContext.newInstance("generated"); }
Example #9
Source File: ReadIT.java From bookapp-cqrs with Apache License 2.0 | 6 votes |
@Test public void test() { EntityManager em = Persistence.createEntityManagerFactory( "ch.bfh.swos.bookapp.book.domain").createEntityManager(); Query q = em.createQuery("select a from Author a"); @SuppressWarnings("unchecked") List<Author> foundAuthors = q.getResultList(); Author firstAuthor = foundAuthors.get(0); Assert.assertTrue(firstAuthor.getLastname().equals("Tolkien")); List<Book> foundBooks = new ArrayList<Book>(firstAuthor.getBooks()); Book firstBook = foundBooks.get(0); Assert.assertTrue(firstBook.getTitle().startsWith("Der Herr der Ringe")); }
Example #10
Source File: AddressbookExampleUIEx.java From vaadinator with Apache License 2.0 | 6 votes |
@Override protected PresenterFactory obtainPresenterFactory(String contextPath) { if (presenterFactory == null) { // simple, overwrite method for e.g. Spring / CDI / ... // Entity-Manager NUR Thread-Safe, wenn er injected wird wie hier AddressService addressService; TeamService teamService; EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("AddressbookExample"); AddressDaoPlain addressDaoPlain = new AddressDaoPlain(entityManagerFactory); addressService = new AddressServicePlain(entityManagerFactory, addressDaoPlain); TeamDaoPlain teamDaoPlain = new TeamDaoPlain(entityManagerFactory); teamService = new TeamServicePlain(entityManagerFactory, teamDaoPlain); VaadinViewFactoryEx viewFactory = new VaadinViewFactoryEx(); presenterFactory = new PresenterFactoryEx(new HashMap<String, Object>(), viewFactory, addressService, teamService); viewFactory.setPresenterFactory(presenterFactory); } return presenterFactory; }
Example #11
Source File: EntityManagerProvider.java From database-rider with Apache License 2.0 | 6 votes |
private void init(String unitName) { if (emf == null) { log.debug("creating emf for unit {}", unitName); Map<String,String> dbConfig = getDbPropertyConfig(); log.debug("using dbConfig '{}' to create emf", dbConfig); emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig); em = emf.createEntityManager(); tx = em.getTransaction(); if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) { conn = ((SessionImpl) em.unwrap(Session.class)).connection(); } else{ /** * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager */ tx.begin(); conn = em.unwrap(Connection.class); tx.commit(); } } emf.getCache().evictAll(); }
Example #12
Source File: TestNominalAttributeResourceFacadeImp.java From AIDR with GNU Affero General Public License v3.0 | 6 votes |
@BeforeClass public static void setUpClass() { entityManager = Persistence.createEntityManagerFactory( "ProjectDBManagerTest-ejbPU").createEntityManager(); userResourceFacadeImp = new UsersResourceFacadeImp(); crisisResourceFacadeImp = new CollectionResourceFacadeImp(); crisisTypeResourceFacadeImp = new CrisisTypeResourceFacadeImp(); userResourceFacadeImp.setEntityManager(entityManager); nominalAttributeResourceFacadeImp = new NominalAttributeResourceFacadeImp(); crisisResourceFacadeImp.setEntityManager(entityManager); crisisTypeResourceFacadeImp.setEntityManager(entityManager); nominalAttributeResourceFacadeImp.setEntityManager(entityManager); user = new UsersDTO("userDBTest"+new Date(), "normal"+new Date()); entityManager.getTransaction().begin(); user = userResourceFacadeImp.addUser(user); entityManager.getTransaction().commit(); }
Example #13
Source File: EntityManagerProvider.java From database-rider with Apache License 2.0 | 6 votes |
private void init(String unitName) { if (emf == null) { log.debug("creating emf for unit {}", unitName); Map<String,String> dbConfig = getDbPropertyConfig(); log.debug("using dbConfig '{}' to create emf", dbConfig); emf = dbConfig == null ? Persistence.createEntityManagerFactory(unitName) : Persistence.createEntityManagerFactory(unitName, dbConfig); em = emf.createEntityManager(); tx = em.getTransaction(); if (isHibernateOnClasspath() && em.getDelegate() instanceof Session) { conn = ((SessionImpl) em.unwrap(Session.class)).connection(); } else{ /** * see here:http://wiki.eclipse.org/EclipseLink/Examples/JPA/EMAPI#Getting_a_JDBC_Connection_from_an_EntityManager */ tx.begin(); conn = em.unwrap(Connection.class); tx.commit(); } } emf.getCache().evictAll(); }
Example #14
Source File: TestMiscResourceFacadeImp.java From AIDR with GNU Affero General Public License v3.0 | 6 votes |
@BeforeClass public static void setUpBeforeClass() { miscResourceFacadeImp = new MiscResourceFacadeImp(); documentNominalLabelResourceFacadeImp = new DocumentNominalLabelResourceFacadeImp(); documentResourceFacadeImp = new DocumentResourceFacadeImp(); modelFamilyResourceFacadeImp = new ModelFamilyResourceFacadeImp(); crisisResourceFacadeImp = new CollectionResourceFacadeImp(); crisisTypeResourceFacadeImp = new CrisisTypeResourceFacadeImp(); nominalAttributeResourceFacadeImp = new NominalAttributeResourceFacadeImp(); userResourceFacadeImp = new UsersResourceFacadeImp(); nominalLabelResourceFacadeImp = new NominalLabelResourceFacadeImp(); entityManager = Persistence.createEntityManagerFactory( "ProjectDBManagerTest-ejbPU").createEntityManager(); miscResourceFacadeImp.setEntityManager(entityManager); modelFamilyResourceFacadeImp.setEntityManager(entityManager); crisisResourceFacadeImp.setEntityManager(entityManager); crisisTypeResourceFacadeImp.setEntityManager(entityManager); userResourceFacadeImp.setEntityManager(entityManager); nominalAttributeResourceFacadeImp.setEntityManager(entityManager); documentResourceFacadeImp.setEntityManager(entityManager); documentNominalLabelResourceFacadeImp.setEntityManager(entityManager); nominalLabelResourceFacadeImp.setEntityManager(entityManager); }
Example #15
Source File: JPAEntityManagerModule.java From james-project with Apache License 2.0 | 6 votes |
@Provides @Singleton public EntityManagerFactory provideEntityManagerFactory(JPAConfiguration jpaConfiguration) { HashMap<String, String> properties = new HashMap<>(); properties.put("openjpa.ConnectionDriverName", jpaConfiguration.getDriverName()); properties.put("openjpa.ConnectionURL", jpaConfiguration.getDriverURL()); jpaConfiguration.getCredential() .ifPresent(credential -> { properties.put("openjpa.ConnectionUserName", credential.getUsername()); properties.put("openjpa.ConnectionPassword", credential.getPassword()); }); List<String> connectionFactoryProperties = new ArrayList<>(); connectionFactoryProperties.add("TestOnBorrow=" + jpaConfiguration.isTestOnBorrow()); jpaConfiguration.getValidationQueryTimeoutSec() .ifPresent(timeoutSecond -> connectionFactoryProperties.add("ValidationTimeout=" + timeoutSecond * 1000)); jpaConfiguration.getValidationQuery() .ifPresent(validationQuery -> connectionFactoryProperties.add("ValidationSQL='" + validationQuery + "'")); properties.put("openjpa.ConnectionFactoryProperties", Joiner.on(", ").join(connectionFactoryProperties)); return Persistence.createEntityManagerFactory("Global", properties); }
Example #16
Source File: Library.java From rhpam-7-openshift-image with Apache License 2.0 | 5 votes |
synchronized Library init() { if (emf == null) { emf = Persistence.createEntityManagerFactory("library"); new Init(emf).transact(); } return this; }
Example #17
Source File: DataNucleusEntityManagerFactory.java From lb-karaf-examples-jpa with Apache License 2.0 | 5 votes |
/** * * @param persistenceUnit * @return */ public static EntityManagerFactory createEntityManagerFactory(String persistenceUnit) { return Persistence.createEntityManagerFactory(persistenceUnit, new HashMap<Object,Object>() {{ put( "datanucleus.primaryClassLoader", DataNucleusEntityManagerFactory.class.getClassLoader()); put( "datanucleus.plugin.pluginRegistryClassName", OSGiPluginRegistry.class.getName()); }}); }
Example #18
Source File: EntityManagerFactoryDecoratorTest.java From jpa-unit with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "unchecked", "rawtypes" }) @Before public void prepareMocks() { mockStatic(Persistence.class); when(Persistence.createEntityManagerFactory(eq(UNIT_NAME), eq(PERSISTENCE_PROPERTIES))).thenReturn(factory); when(invocation.getContext()).thenReturn(ctx); when(invocation.getTestClass()).thenReturn((Class) getClass()); when(ctx.getDescriptor()).thenReturn(descriptor); when(descriptor.getUnitName()).thenReturn(UNIT_NAME); when(descriptor.getProperties()).thenReturn(PERSISTENCE_PROPERTIES); }
Example #19
Source File: PersistenceModule.java From nomulus with Apache License 2.0 | 5 votes |
private static EntityManagerFactory create(Map<String, String> properties) { // If there are no annotated classes, we can create the EntityManagerFactory from the generic // method. Otherwise we have to use a more tailored approach. Note that this adds to the set // of annotated classes defined in the configuration, it does not override them. EntityManagerFactory emf = Persistence.createEntityManagerFactory( PERSISTENCE_UNIT_NAME, ImmutableMap.copyOf(properties)); checkState( emf != null, "Persistence.createEntityManagerFactory() returns a null EntityManagerFactory"); return emf; }
Example #20
Source File: App.java From jqm with Apache License 2.0 | 5 votes |
@Override public void start() { log.info("Starting payload"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("marsu-pu"); EntityManager em = emf.createEntityManager(); log.info("Running query"); em.createQuery("SELECT e from Entity e"); if (this.getParameters().size() == 0) { // We use non-standard datasource names during tests Properties p = new Properties(); String dbName = System.getenv("DB"); dbName = (dbName == null ? "hsqldb" : dbName); p.put("javax.persistence.nonJtaDataSource", "jdbc/" + dbName); JqmClientFactory.setProperties(p); // End of datasource name change log.info("Queuing again - with parameter and through the full API"); JobRequest jd = new JobRequest("jqm-test-em", "marsu"); jd.addParameter("stop", "1"); JqmClientFactory.getClient().enqueue(jd); } log.info("End of payload"); }
Example #21
Source File: EntityManagerFactoryAccessor.java From apiman with Apache License 2.0 | 5 votes |
@PostConstruct public void postConstruct() { Map<String, String> properties = new HashMap<>(); // Get properties from apiman.properties Map<String, String> cp = jpaProperties.getAllHibernateProperties(); if (cp != null) { properties.putAll(cp); } // Get two specific properties from the System (for backward compatibility only) String s = properties.get("hibernate.hbm2ddl.auto"); //$NON-NLS-1$ if (s == null) { s = "validate"; //$NON-NLS-1$ } String autoValue = System.getProperty("apiman.hibernate.hbm2ddl.auto", s); //$NON-NLS-1$ s = properties.get("hibernate.dialect"); //$NON-NLS-1$ if (s == null) { s = "org.hibernate.dialect.H2Dialect"; //$NON-NLS-1$ } String dialect = System.getProperty("apiman.hibernate.dialect", s); //$NON-NLS-1$ properties.put("hibernate.hbm2ddl.auto", autoValue); //$NON-NLS-1$ properties.put("hibernate.dialect", dialect); //$NON-NLS-1$ // First try using standard JPA to load the persistence unit. If that fails, then // try using hibernate directly in a couple ways (depends on hibernate version and // platform we're running on). try { emf = Persistence.createEntityManagerFactory("apiman-manager-api-jpa", properties); //$NON-NLS-1$ } catch (Throwable t1) { try { emf = new HibernatePersistenceProvider().createEntityManagerFactory("apiman-manager-api-jpa", properties); //$NON-NLS-1$ } catch (Throwable t3) { throw t1; } } }
Example #22
Source File: JPAConfig.java From quarkus with Apache License 2.0 | 5 votes |
EntityManagerFactory get() { if (value == null) { synchronized (this) { if (closed) { throw new IllegalStateException("Persistence unit is closed"); } if (value == null) { value = Persistence.createEntityManagerFactory(name); } } } return value; }
Example #23
Source File: NotStandardTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
@BeforeEach public void init() { emFactory = Persistence.createEntityManagerFactory("DB"); em = emFactory.createEntityManager(); valFactory = Validation.buildDefaultValidatorFactory(); validator = valFactory.getValidator(); }
Example #24
Source File: PersistenceProvider.java From jerseyoauth2 with MIT License | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) public PersistenceProvider() { Map params = new HashMap(); params.put("hibernate.hbm2ddl.auto","create-drop"); params.put("hibernate.cache.use_second_level_cache","false"); params.put("hibernate.dialect","org.hibernate.dialect.DerbyTenSevenDialect"); emf = Persistence.createEntityManagerFactory("authsrv", params ); }
Example #25
Source File: SingletonEntityManager.java From testfun with Apache License 2.0 | 5 votes |
private synchronized EntityManager getEntityManager() { if (entityManager == null) { Map<String, DataSource> config = new HashMap<>(); config.put(AvailableSettings.DATASOURCE, SingletonDataSource.getDataSource()); EntityManagerFactory emf = Persistence.createEntityManagerFactory(PersistenceXml.getInstnace().getPersistenceUnitName(), config); entityManager = emf.createEntityManager(); } return entityManager; }
Example #26
Source File: EditorUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); Editor editor = generateTestData(); persistTestData(entityManagerFactory, editor); loadAndVerifyTestData(entityManagerFactory, editor); }
Example #27
Source File: MCRJPABootstrapper.java From mycore with GNU General Public License v3.0 | 5 votes |
public static void initializeJPA(String persistenceUnitName, Map<?, ?> properties) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory( Optional.ofNullable(persistenceUnitName).orElse(PERSISTENCE_UNIT_NAME), properties); checkFactory(entityManagerFactory); MCREntityManagerProvider.init(entityManagerFactory); }
Example #28
Source File: GetReferenceMySQLManualTest.java From tutorials with MIT License | 5 votes |
@BeforeAll public static void setup() { // close some specific loggers so that we can clearly see Hibernate: SQL queries ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_mysql"); }
Example #29
Source File: GetReferencePostgreSQLManualTest.java From tutorials with MIT License | 5 votes |
@BeforeAll public static void setup() { // close some specific loggers so that we can clearly see Hibernate: SQL queries ((Logger) LoggerFactory.getLogger("org.hibernate.SQL")).setLevel(Level.OFF); ((Logger) LoggerFactory.getLogger("org.hibernate.type.descriptor.sql")).setLevel(Level.OFF); ((Logger) LoggerFactory.getLogger("org.hibernate.stat")).setLevel(Level.OFF); entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.entitymanager.game_player_postgresql"); }
Example #30
Source File: Migrate.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
public void migrate7() { 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(Site.PERSISTENCE_UNIT, properties); EntityManager em = factory.createEntityManager(); em.getTransaction().begin(); try { em.createNativeQuery("Update ChatChannel set alias = name").executeUpdate(); em.createNativeQuery("Update Forum set alias = name").executeUpdate(); em.createNativeQuery("Update BotInstance set alias = name").executeUpdate(); em.createNativeQuery("Update Graphic set alias = name").executeUpdate(); em.createNativeQuery("Update Domain set alias = name").executeUpdate(); em.createNativeQuery("Update IssueTracker set alias = name").executeUpdate(); em.createNativeQuery("Update Analytic set alias = name").executeUpdate(); em.createNativeQuery("Update Script set alias = name").executeUpdate(); em.createNativeQuery("Update Avatar set alias = name").executeUpdate(); em.getTransaction().commit(); } catch (Exception exception) { exception.printStackTrace(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); factory.close(); } }