@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()); }
/** * retrieves the <code>RolesPermission</code> by the role. * * @param role * the role * @return userPermissions the list of permissions of the user * */ public static Set<String> getPermission(String role) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<RolePermission> q = cb.createQuery(RolePermission.class); Root<RolePermission> c = q.from(RolePermission.class); q.select(c).where(cb.equal(c.get("roleName"), role)); TypedQuery<RolePermission> query = em.createQuery(q); List<RolePermission> permissions = query.getResultList(); Set<String> userPermissions = new HashSet<String>(); for (RolePermission permission : permissions) userPermissions.add(permission.getPermission()); tx.commit(); em.close(); return userPermissions; }
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(); }
public static User getUser(String username) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> q = cb.createQuery(User.class); Root<User> c = q.from(User.class); q.select(c).where(cb.equal(c.get("username"), username)); TypedQuery<User> query = em.createQuery(q); List<User> users = query.getResultList(); em.close(); LOGGER.info("found " + users.size() + " users with username " + username); if (users.size() == 1) return users.get(0); else return null; }
@Test public void jpaWithActiveSpanOnlyWithParent() { try (Scope activeSpan = mockTracer.buildSpan("parent").startActive(true)) { 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(9, finishedSpans.size()); checkSameTrace(finishedSpans); assertNull(mockTracer.scopeManager().active()); }
/** * @param args the command line arguments */ @PersistenceUnit public static void main(String[] args) { System.out.println("Creating entity information..."); EntityManager entityManager = Persistence.createEntityManagerFactory("DataAppLibraryPULocal").createEntityManager(); EntityTransaction et = entityManager.getTransaction(); et.begin(); loadDiscountRate(entityManager); loadRegion(entityManager); loadRole(entityManager); loadTransmission(entityManager); loadProductType(entityManager); loadEngine(entityManager); loadProduct(entityManager); et.commit(); EntityManager specialEntityManager = new InitialLoadEntityManagerProxy(entityManager); SalesSimulator simulator = new SalesSimulator(specialEntityManager); Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); cal.clear(); cal.set(year-1, 0, 1, 0, 0, 0); // go back to begining of year, 3 years ago System.out.println("Creating historical data..."); System.out.println(" This may take 5 to 15min depending on machine speed."); simulator.run(cal.getTime(), new Date()); entityManager.close(); }
/** Creates new form PreferencesDialog */ public PreferencesDialog() { initComponents(); emf = Persistence.createEntityManagerFactory("GeoImageViewerPU"); EntityManager em = emf.createEntityManager(); Query q = em.createNamedQuery("Preferences.findAll"); prefs = q.getResultList(); em.close(); setTitle("SUMO Preferences"); initTable(); }
public PluginsManager() { plugins = new HashMap<String, Plugins>(); actions = new HashMap<String, ISumoAction>(); emf = Persistence.createEntityManagerFactory("GeoImageViewerPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Query q = em.createQuery("select p.className from Plugins p"); List<String> dbPuginNames = q.getResultList(); em.getTransaction().commit(); populateDatabase(dbPuginNames); em.getTransaction().begin(); Query q2 = em.createQuery("select p from Plugins p"); List<Plugins> dbPlugins = q2.getResultList(); dbPlugins = q2.getResultList(); em.getTransaction().commit(); em.close(); List<ISumoAction> landActions=getDynamicActionForLandmask(); parseActions(dbPlugins); parseActionsLandMask(landActions); }
/** * Set up memory database and insert data from test-dataset.xml * * @throws DatabaseUnitException * @throws HibernateException * @throws SQLException */ @BeforeClass public static void initEntityManager() throws HibernateException, DatabaseUnitException, SQLException { entityManagerFactory = Persistence.createEntityManagerFactory("listing-test-db"); entityManager = entityManagerFactory.createEntityManager(); connection = new DatabaseConnection(((SessionImpl) (entityManager.getDelegate())).connection()); connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory()); InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(datasetXml); if (inputStream != null) { FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder(); flatXmlDataSetBuilder.setColumnSensing(true); dataset = flatXmlDataSetBuilder.build(inputStream); DatabaseOperation.CLEAN_INSERT.execute(connection, dataset); } }
@BeforeClass public static void connect() throws DatabaseException { factory = Persistence.createEntityManagerFactory(persistencUnitName); assertNotNull(factory); em = factory.createEntityManager(); assertNotNull(em); tx = em.getTransaction(); assertNotNull(tx); edao.setEntityManager(em); tx.begin(); for (int i = 1; i <= 7; i++) { if (edao.findById(i) == null) edao.createEnumeration(i); } tx.commit(); }
/** * retrieves the list of roles for a given username. * * @param username * the username * @return userRoles the roles * */ public static Set<String> getRoles(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(); Set<String> userRoles = new HashSet<String>(); em.close(); for (UserRole role : roles) userRoles.add(role.getRoleName()); return userRoles; }
/** * @see fr.univlorraine.ecandidat.services.siscol.SiScolGenericService#getVersion() */ @Override public Version getVersion() throws SiScolException { try { EntityManagerFactory emf = Persistence.createEntityManagerFactory("pun-jpa-siscol"); EntityManager em = emf.createEntityManager(); Query query = em.createQuery("Select a from VersionApo a where a.datCre is not null order by a.datCre desc", VersionApo.class).setMaxResults(1); List<VersionApo> listeVersionApo = query.getResultList(); em.close(); if (listeVersionApo != null && listeVersionApo.size() > 0) { VersionApo versionApo = listeVersionApo.get(0); return new Version(versionApo.getId().getCodVer()); } else { return null; } } catch (Exception e) { throw new SiScolException("SiScol database error on getVersion", e.getCause()); } }
@Test public void jpa_with_active_span_only() { 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.activeSpan()); }
/** * Renvoie les voeux OPI d'un individu * * @param indOpi * @return * @throws SiScolException */ private List<VoeuxIns> getVoeuxApogee(IndOpi indOpi) throws SiScolException { try { String queryString = "Select a from VoeuxIns a where a.id.codIndOpi = " + indOpi.getCodIndOpi(); logger.debug("Vérification des voeux " + queryString); EntityManagerFactory emf = Persistence.createEntityManagerFactory("pun-jpa-siscol"); EntityManager em = emf.createEntityManager(); Query query = em.createQuery(queryString, VoeuxIns.class); List<VoeuxIns> listeSiScol = query.getResultList(); em.close(); return listeSiScol; } catch (Exception e) { throw new SiScolException("SiScol database error on getVoeuxApogee", e); } }
static EntityManagerFactory init() { try { Map<String, Object> props = new HashMap<>(); props.put("javax.persistence.jdbc.driver", "org.h2.Driver"); props.put("javax.persistence.jdbc.url", "jdbc:h2:mem:test"); // in-memory db props.put("javax.persistence.schema-generation.database.action", "drop-and-create"); // create brand-new db schema in memory props.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); props.put("hibernate.show_sql", "false"); // Set this to true to debug any DB failures props.put("hibernate.hbm2ddl.halt_on_error", Boolean.TRUE); // Cause test to fail in case of any errors during db creation emf = Persistence.createEntityManagerFactory("osc-server", props); return emf; } catch (Throwable ex) { System.out.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
/** * Returns the singleton EntityManagerFactory instance for accessing the * default database. * * @return the singleton EntityManagerFactory instance * @throws NamingException * if a naming exception occurs during initialization * @throws SQLException * if a database occurs during initialization * @throws IOException */ public static synchronized EntityManagerFactory getEntityManagerFactory() throws NamingException, SQLException, IOException { if (entityManagerFactory == null) { InitialContext ctx = new InitialContext(); BasicDataSource ds = new BasicDataSource(); JsonNode credentials = readCredentialsFromEnvironment(); ds.setDriverClassName(credentials.get("driver").asText()); ds.setUrl(credentials.get("url").asText()); ds.setUsername(credentials.get("user").asText()); ds.setPassword(credentials.get("password").asText()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, ds); entityManagerFactory = Persistence.createEntityManagerFactory( PERSISTENCE_UNIT_NAME, properties); } return entityManagerFactory; }
@Test public void jpa_with_parent_and_active_span_only() { try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) { EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("jpa_active_span_only"); 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()); }
@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(); }
/** * 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); }
private void btn_kontrolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_kontrolActionPerformed // TODO add your handling code here: EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("SELECT m FROM Musteri m"); List<Musteri> musteriler = q.getResultList(); for (Musteri musteri : musteriler) { Path p= Paths.get("musteriler\\"+musteri.getId()+".txt"); try { p.toRealPath(); } catch (IOException ex) { System.out.println(musteri.getId()+" numaralı müsteri dosyası bulunamadı"); } } }
/** * Initialize the EntityManagerFactory for the given configuration. * @throws javax.persistence.PersistenceException in case of JPA initialization errors */ @Override protected EntityManagerFactory createNativeEntityManagerFactory() throws PersistenceException { if (logger.isInfoEnabled()) { logger.info("Building JPA EntityManagerFactory for persistence unit '" + getPersistenceUnitName() + "'"); } PersistenceProvider provider = getPersistenceProvider(); if (provider != null) { // Create EntityManagerFactory directly through PersistenceProvider. EntityManagerFactory emf = provider.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap()); if (emf == null) { throw new IllegalStateException( "PersistenceProvider [" + provider + "] did not return an EntityManagerFactory for name '" + getPersistenceUnitName() + "'"); } return emf; } else { // Let JPA perform its standard PersistenceProvider autodetection. return Persistence.createEntityManagerFactory(getPersistenceUnitName(), getJpaPropertyMap()); } }
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(); }
public Soru1() { initComponents(); ///SORGULAMA EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("SELECT d FROM Doktor d"); doktorlar = q.getResultList(); for (Doktor dr : doktorlar) { cmb_doktorlar.addItem(dr.getAdi() + " " + dr.getSoyadi()); } dtm = new DefaultTableModel(); dtm.setColumnIdentifiers(new Object[]{"ID", "ADI", "SOYADI", "DOkTOR ID"}); 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); ///// }
private void btn_hastaekleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_hastaekleActionPerformed // TODO add your handling code here: Hasta newhasta = new Hasta(); newhasta.setId(Integer.parseInt(txt_hastaid.getText())); newhasta.setAdi(txt_hastaadi.getText()); newhasta.setSoyadi(txt_hastaadi.getText()); newhasta.setIdDoktor(doktorlar.get(cmb_doktorlar.getSelectedIndex()).getId()); ///EKLEME EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(newhasta); em.getTransaction().commit(); dtm.setRowCount(0); Query 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); ///// }
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); }
public EntityManagerFactory getEntityManagerFactory(String persistenceUnitName) { if (emf == null) { emf = Persistence.createEntityManagerFactory(persistenceUnitName); } return emf; }
private void btn_tutarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_tutarActionPerformed // TODO add your handling code here: // TODO add your handling code here: EntityManagerFactory emf = Persistence.createEntityManagerFactory("BP2_LAB2PU"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("SELECT m FROM Musteri m"); List<Musteri> musteriler = q.getResultList(); for (Musteri musteri : musteriler) { q = em.createQuery("SELECT s FROM Satis s WHERE s.idMusteri=:id"); q.setParameter("id", musteri.getId()); List<Satis> satislar = q.getResultList(); int toplam = 0; for (Satis satis : satislar) { toplam += satis.getTutar(); } System.out.println(musteri.getId()+" "+toplam); } // // Query q = em.createQuery("SELECT sum(s.tutar) FROM Satis s Group By s.idMusteri "); // List<Object> satislar = q.getResultList(); // for (Object satis : satislar) { // System.out.println(""+(Long)satis); // } }
/** * Gets the emf. * * @return the emf */ private static EntityManagerFactory getEmf() { if (emf == null) { String persistenceUnitName = loadPersistentUnitName(); emf = Persistence.createEntityManagerFactory(persistenceUnitName); } return emf; }
@Test public void selectHqlTest() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start"); EntityManager manager = factory.createEntityManager(); Query query = manager.createQuery("Select c from Cidade c"); List<Cidade> cidades = query.getResultList(); for (Cidade cidade : cidades) { System.out.println(cidade.getNome()); System.out.println(cidade.getId()); System.out.println(cidade.getUf().getNome()); } }
public static void main(String[] args) throws Exception { // Get the entity manager EntityManager em = Persistence.createEntityManagerFactory("company-provider").createEntityManager(); em.getTransaction().begin(); em.createNativeQuery("PRAGMA foreign_keys=ON").executeUpdate(); em.getTransaction().commit(); // Search in departments by name BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Write the department's name: "); String name = reader.readLine(); System.out.println("Matching departments:"); Query q1 = em.createNativeQuery("SELECT * FROM departments WHERE name LIKE ?", Department.class); q1.setParameter(1, "%" + name + "%"); List<Department> deps = (List<Department>) q1.getResultList(); // Print the departments for (Department department : deps) { System.out.println(department); } // Get just one department // Only use this while looking by unique fields, if not, // you could get duplicate results System.out.print("Write the department's ID: "); int dep_id = Integer.parseInt(reader.readLine()); Query q2 = em.createNativeQuery("SELECT * FROM departments WHERE id = ?", Department.class); q2.setParameter(1, dep_id); Department dep = (Department) q2.getSingleResult(); // Print the department System.out.println(dep); // Close the entity manager em.close(); }
/** * gets an author from the database by determining the type of the provided id. if no author is present it builds one from the id. * @param id the author identifier * @return the author retrieved from the database or build with the identifier * @throws JDOMException thrown upon parsing the source response * @throws IOException thrown upon reading profiles from disc * @throws SAXException thrown when parsing the files from disc */ public PublicationAuthor retrieveAuthor(String id) throws JDOMException, IOException, SAXException { typeOfID = determineID(id); LOGGER.info("given ID: " + id + " is of type " + typeOfID); EntityManagerFactory emf = Persistence.createEntityManagerFactory("publicationAuthors"); EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<PublicationAuthor> q = cb.createQuery(PublicationAuthor.class); Root<PublicationAuthor> c = q.from(PublicationAuthor.class); List<Predicate> predicates = new ArrayList<>(); if (typeOfID.equals("surname")) { if (id.contains(",")) { predicates.add(cb.equal(c.get("surname"),id.substring(0,id.indexOf(",")))); predicates.add(cb.equal(c.get("firstname"),id.substring(id.indexOf(",")+1))); LOGGER.info("retriving surname, firstname from database for " + id); } else if (id.contains(" ")) { predicates.add(cb.equal(c.get("firstname"),id.substring(0,id.indexOf(" ")))); predicates.add(cb.equal(c.get("surname"),id.substring(id.indexOf(" ")+1))); LOGGER.info("retrieving firstname surname from database for " + id); } else { predicates.add(cb.equal(c.get("surname"), id)); LOGGER.info("retrieving surname from database for " + id); } } predicates.add(cb.equal(c.get(typeOfID), id)); q.select(c).where(cb.equal(c.get(typeOfID), id)); TypedQuery<PublicationAuthor> query = em.createQuery(q); List<PublicationAuthor> authors = query.getResultList(); em.close(); if (authors.size() == 1) { LOGGER.info("found author in database"); this.author = authors.get(0); return author; } LOGGER.info("no match in database"); return buildAuthor(id); }
private EntityManagerFactory createTestEMF() { Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver"); properties.put("javax.persistence.jdbc.url", "jdbc:derby:memory:TEST;create=true"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("tasklist", properties); return emf; }
private EntityManagerFactory createTestEMF() { Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver"); properties.put("javax.persistence.jdbc.url", "jdbc:derby:target/test;create=true"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("tasklist", properties); return emf; }
@Test public void updateTest() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start"); EntityManager manager = factory.createEntityManager(); Cidade cidade = manager.find(Cidade.class, 2L); cidade.setNome("Maringa"); manager.getTransaction().begin(); manager.persist(cidade); manager.getTransaction().commit(); factory.close(); }
/** * Sets up a {@link SimpleJpaRepository} instance. */ @Before public void setUp() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa.sample.plain"); em = factory.createEntityManager(); userRepository = new SimpleJpaRepository<User, Long>(User.class, em); em.getTransaction().begin(); }
private static void initEntityManagerFactory(DataSource dataSource) { logger.debug(DEBUG_INITIALIZING_ENTITY_MANAGER_FACTORY); Map<Object, Object> properties = new HashMap<>(); properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, dataSource); EntityManagerFactoryProvider.entityManagerFactory = Persistence .createEntityManagerFactory(PublicSourcingPersistenceUnit.NAME, properties); logger.debug(DEBUG_ENTITY_MANAGER_FACTORY_INITIALIZED); }
/** * Get the entity manager factory. * @return The entity manager factory. */ static EntityManagerFactory getEMF() { if (emf == null) { HashMap<String, String> persistenceProperties = EMFManager.persistenceProperties; if (persistenceProperties == null) { persistenceProperties = createPersistencePropertiesFromJavaEnv(); } emf = Persistence.createEntityManagerFactory("tools.descartes.petsupplystore.persistence", persistenceProperties); } return emf; }
public static JpaMetamodelRedGProvider fromPersistenceUnit(String perstistenceUnitName) { Properties properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(perstistenceUnitName, properties); EntityManager entityManager = entityManagerFactory.createEntityManager(); return new JpaMetamodelRedGProvider(entityManager.getMetamodel()); }