Java Code Examples for javax.persistence.EntityManagerFactory.createEntityManager()

The following are Jave code examples for showing how to use createEntityManager() of the javax.persistence.EntityManagerFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: bibliometrics   File: RolePermissionDAO.java   Source Code and License Vote up 7 votes
/**
 * 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;
}
 
Example 2
Project: java-jdbc   File: HibernateTest.java   Source Code and License Vote up 6 votes
@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());
}
 
Example 3
Project: bibliometrics   File: AuthorBuilder.java   Source Code and License Vote up 6 votes
/**
   * 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);
  }
 
Example 4
Project: testee.fi   File: JpaInjectionServicesImpl.java   Source Code and License Vote up 6 votes
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);
    }
}
 
Example 5
Project: bibliometrics   File: UserRoleDAO.java   Source Code and License Vote up 6 votes
/**
 * 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;
}
 
Example 6
Project: Java_Swing_Programming   File: Frm_KullaniciSayfasi.java   Source Code and License Vote up 6 votes
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();
    
    
}
 
Example 7
Project: Java_Swing_Programming   File: Soru1.java   Source Code and License Vote up 6 votes
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);


}
 
Example 8
Project: optashift-employee-rostering   File: OptaShiftEmployeeRosteringBenchmarkApp.java   Source Code and License Vote up 5 votes
private static List<Roster> generateRosters() {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("optashift-employee-rostering-persistence-unit");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    RosterGenerator rosterGenerator = new RosterGenerator(entityManager);

    List<Roster> rosterList = new ArrayList<>();
    rosterList.add(rosterGenerator.generateRoster(10, 7, false));
    rosterList.add(rosterGenerator.generateRoster(80, (28 * 4), false));

    entityManager.close();
    entityManagerFactory.close();
    return rosterList;
}
 
Example 9
Project: BecomeJavaHero   File: JPACategoryService.java   Source Code and License Vote up 5 votes
@Override
public Category getCategoryById(int id) {
	EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	// begining of transaction
	em.getTransaction().begin();
	
	return em.find(Category.class, id);
}
 
Example 10
Project: Java_Swing_Programming   File: Frm_Login.java   Source Code and License Vote up 5 votes
private void btn_girisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_girisActionPerformed
    // TODO add your handling code here:
    String kullaniciad = txt_kullaniciAdi.getText();
    String sifre = String.copyValueOf(txtp_sifre.getPassword());
    boolean girisyap = false;
    USER_1 login=null;
    
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
    EntityManager em = emf.createEntityManager();

    Query q = em.createQuery("SELECT u FROM USER_1 u WHERE u.kullaniciAdi=:kad AND u.sifre=:sif");
    
    q.setParameter("kad", kullaniciad);
    q.setParameter("sif", sifre);
    
    login=(USER_1)q.getSingleResult();
    
    if(login!=null)
    {
       loginuser=login;
      Frm_KullaniciSayfasi newkullanicisayfasi = new Frm_KullaniciSayfasi();
        newkullanicisayfasi.setVisible(true);
        this.dispose();
    
    }
    else
    {
      JOptionPane.showMessageDialog(rootPane, "Kullanici Adi ya da Şifre Geçersiz! ");
    }
  
}
 
Example 11
Project: aries-jpa   File: TaskServiceImplTest.java   Source Code and License Vote up 5 votes
private EmSupplier createEmSupplier(EntityManagerFactory emf) {
    final EntityManager em = emf.createEntityManager();
    EmSupplier emSupplier = new EmSupplier() {
        public void preCall() {
        }

        public EntityManager get() {
            return em;
        }

        public void postCall() {
        }
    };
    return emSupplier;
}
 
Example 12
Project: bibliometrics   File: PublicationAuthorDAO.java   Source Code and License Vote up 5 votes
public static List<PublicationAuthor> getAuthors() {
	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);
	q.select(c).where(cb.like(c.<String>get("surname"), "%"));
	TypedQuery<PublicationAuthor> query = em.createQuery(q);
	List<PublicationAuthor> authors = query.getResultList();
	em.close();
	return authors;
}
 
Example 13
Project: bibliometrics   File: UserDAO.java   Source Code and License Vote up 5 votes
/**
 * 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;
}
 
Example 14
Project: Java_Swing_Programming   File: Soru2.java   Source Code and License Vote up 5 votes
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
         EntityManagerFactory emf=Persistence.createEntityManagerFactory("BP2_LAB2PU");
         EntityManager em=emf.createEntityManager();
         Query q=em.createQuery("SELECT k FROM Personel k");
         List<Personel>personeller=q.getResultList();
      //   ArrayList<String> paths=new ArrayList();
         for (Personel personel : personeller) {
             try {
                 //   paths.add(personel.getAdi());
                 Path p =Paths.get(personel.getAdi());
                 p.toRealPath();
             } catch (IOException ex) {
                 Logger.getLogger(Soru2.class.getName()).log(Level.SEVERE, null, ex);
             }
        }
//         
//         for (String path : paths) {
//             try {
//                 Path p=Paths.get(path);
//                 p.toRealPath();
//             } catch (IOException ex) {
//                 System.out.println(path+" Müşterisine Ait Bilgi Bulunamadı.");
//             }
//        }
         
         
    }
 
Example 15
Project: Java_Swing_Programming   File: Frm_KullaniciSayfasi.java   Source Code and License Vote up 5 votes
private void btn_ekleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ekleActionPerformed
    // TODO add your handling code here:
    if (tbl_kisiliste.getSelectedRow() < 0) {
        JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz");
        return;
    }
    int id = (int) dtm1.getValueAt(tbl_kisiliste.getSelectedRow(), 0);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
    EntityManager em = emf.createEntityManager();

    Query q = em.createQuery("SELECT u FROM USER_1 u WHERE u.id=:id");
    q.setParameter("id", id);

    USER_1 gelen = (USER_1) q.getSingleResult();
    if (gelen == null) {

        return;
    }

    ARKADASLIK yeni = new ARKADASLIK();
    yeni.setId(3);
    yeni.setIdUserIstek(Frm_Login.loginuser.getId());
    yeni.setIdUserKabul(gelen.getId());
    yeni.setKabulDurumu(false);
    em.getTransaction().begin();
    em.persist(yeni);
    em.getTransaction().commit();


}
 
Example 16
Project: BecomeJavaHero   File: App5.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory = Persistence
			.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();

	// begining of transaction
	em.getTransaction().begin();

	// Object used to create more sophisticated conditions
	CriteriaBuilder cb = em.getCriteriaBuilder();
	
	// this object is used to create query object
	CriteriaQuery<Role> cq = cb.createQuery(Role.class);
	
	// We set the root of query (we will use this root to getting values of columns)
	Root<Role> from = cq.from(Role.class);
	
	// we composing query using cb object
	cq.where(cb.equal(from.get("name"), "ordinary"));
	
	// creating query and executing it
	TypedQuery<Role> tq = em.createQuery(cq);
	List<Role> roles = tq.getResultList();
	
	
	for (Role role : roles) {
		System.out.println(role.getName());
	}

	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
Example 17
Project: programacion4-final   File: TypeDoc.java   Source Code and License Vote up 4 votes
public EntityManager getEntityManager(){
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("warehouse_proyectPU");
    EntityManager em = emf.createEntityManager();
    return em;
}
 
Example 18
Project: Java-9-Programming-Blueprints   File: FindFileTask.java   Source Code and License Vote up 4 votes
public FindFileTask(Path startDir, List<PathMatcher> matchers,
        EntityManagerFactory factory) {
    this.startDir = startDir;
    this.em = factory.createEntityManager();
    this.matchers = matchers;
}
 
Example 19
Project: unibave-backend   File: Main.java   Source Code and License Vote up 4 votes
public static void main(String[] args) {
    EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("unibave-jpa");
    //org.hibernate.jpa.HibernatePersistenceProvider
    
    //adiciona
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Aluno ramon = new Aluno();
    ramon.setNome("Ramon");
    ramon.setCidade("Cidade Azul");

    AlunoContato contato = new AlunoContato();
    contato.setTelefone("48999999999");
    //em.persist(contato);
    ramon.addContato(contato);
    
    em.persist(ramon);
    tx.commit();
    em.close();
    //lista
    em = emf.createEntityManager();
    List<Aluno> alunos = em.createNamedQuery("aluno.lista", Aluno.class)
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(a -> {
        System.out.println(a);
        a.getContatos().forEach(System.out::println);
    });
    em.close();
    //lista por cidade
    em = emf.createEntityManager();
    alunos = em.createNamedQuery("aluno.listaPorCidade", Aluno.class)
            .setParameter("cidade", "Cidade Azul")
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(System.out::println);
    em.close();
    //atualiza
    em = emf.createEntityManager();
    tx = em.getTransaction();
    tx.begin();
    ramon = em.find(Aluno.class, ramon.getCodigo());
    ramon.setCidade("Tubarão");
    em.merge(ramon);
    tx.commit();
    //deleta
    tx = em.getTransaction();
    tx.begin();
    em.remove(ramon);
    tx.commit();
    em.close();      
    
    emf.close();
}
 
Example 20
Project: programacion4-final   File: UsersType.java   Source Code and License Vote up 4 votes
public EntityManager getEntityManager(){
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("warehouse_proyectPU");
    EntityManager em = emf.createEntityManager();
    return em;
}