List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:com.edsoft.teknosaproject.bean.ReportBean.java
@Override public void typeListener() { Menus menus;//from ww w . j av a 2s .c o m typeMenu.clear(); brandMenu.clear(); documentMenu.clear(); path = Paths.get(DIR, "AnaDepo", family); //path = Paths.get("D:", "Teknosa", family); fileList = path.toFile().listFiles(); EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager(); em.getTransaction().begin(); Query query = em.createNamedQuery("Menus.findByValued"); typeMenu.add(new SelectItem("", "Seiniz")); for (File file : fileList) { if (file.isDirectory()) { query.setParameter("valued", file.getName()); menus = (Menus) query.getResultList().get(0); menus.setLabel(menus.getLabel1()); menus.setValue(menus.getValued()); typeMenu.add(menus); } } em.getTransaction().commit(); em.close(); }
From source file:com.edsoft.teknosaproject.bean.ReportBean.java
@PostConstruct public void initialize() { list = new ArrayList<>(); filtered = new ArrayList<>(); Menus menus;//from w ww . ja v a 2s .c o m familyMenu = new ArrayList<>(); typeMenu = new ArrayList<>(); brandMenu = new ArrayList<>(); documentMenu = new ArrayList<>(); path = Paths.get(DIR, "AnaDepo"); //path = Paths.get("D:", "Teknosa"); fileList = path.toFile().listFiles(); EntityManager em = Persistence.createEntityManagerFactory("teknosa").createEntityManager(); em.getTransaction().begin(); Query query = em.createNamedQuery("Menus.findByValued"); familyMenu.add(new SelectItem("", "Seiniz")); for (File file : fileList) { if (file.isDirectory()) { query.setParameter("valued", file.getName()); menus = (Menus) query.getResultList().get(0); menus.setValue(menus.getValued()); menus.setLabel(menus.getLabel1()); familyMenu.add(menus); } } em.getTransaction().commit(); em.close(); }
From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java
public synchronized EntityManagerFactory create(File database) throws MetadataException { EntityManagerFactory factory;//from www. j a v a 2 s . c o m String name = "metadata"; Hashtable<String, String> persistProperties = new Hashtable<String, String>(); persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver"); // This swallow all the output log from derby. System.setProperty("derby.stream.error.field", "com.nokia.helium.metadata.DerbyFactoryManagerCreator.DEV_NULL"); persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database.getAbsolutePath()); persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false"); persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK"); persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC"); persistProperties.put("eclipselink.read-only", "true"); persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning"); if (database.exists()) { if (!checkDatabaseIntegrity(database)) { try { FileUtils.forceDelete(database); } catch (java.io.IOException iex) { throw new MetadataException("Failed deleting corrupted db: " + iex, iex); } } else { return Persistence.createEntityManagerFactory(name, persistProperties); } } persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database + ";create=true"); persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables"); persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database"); persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false"); persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK"); persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC"); persistProperties.put("eclipselink.read-only", "true"); factory = Persistence.createEntityManagerFactory(name, persistProperties); EntityManager entityManager = factory.createEntityManager(); // Pushing default data into the current schema try { entityManager.getTransaction().begin(); // Version of the schema is pushed. entityManager.persist(new Version()); // Default set of severity is pushed. for (SeverityEnum.Severity severity : SeverityEnum.Severity.values()) { Severity pData = new Severity(); pData.setSeverity(severity.toString()); entityManager.persist(pData); } entityManager.getTransaction().commit(); } finally { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); entityManager.clear(); } entityManager.close(); } return factory; }
From source file:fr.xebia.demo.wicket.blog.service.GenericService.java
public void delete(T entity) throws ServiceException { try {//from w w w.j a va 2 s. com EntityManager entityManager = currentEntityManager(); entityManager.getTransaction().begin(); Serializable objectId = getObjectId(entity); if (objectId == null) { throw new ServiceException("Entity has no id"); } T loadedEntity = entityManager.find(getObjectClass(), objectId); if (loadedEntity == null) { throw new ServiceException("Entity referenced by id " + objectId + " does not exist"); } entityManager.remove(loadedEntity); commitTransaction(); } catch (PersistenceException e) { logger.error(e.getCause(), e); rollbackTransaction(); throw new ServiceException("Can't delete object", e); } finally { closeEntityManager(); } }
From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployeeRepositoryImplementation.java
@Override public Employee getById(int id) { EntityManager em = entityManagerFactory.createEntityManager(); Employee employee = null;//from w w w .j a va 2 s . co m try { em.getTransaction().begin(); employee = em.find(Employee.class, id); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return employee; }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java
/** * Test persistence.//from ww w .j a va2 s . co m * * @throws Exception the exception */ @Test public void testPersistence() throws Exception { long size = countNews(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); News news = new News(); news.setContent("Spider-man was seen."); news.setHeadline("The amazing spider-man"); news.setFs_id(1l); news.setLanguage("DE"); news.setTeaser("spider-man"); NewsCategory sport = new NewsCategory(); sport.setFs_id(2l); sport.setName("Sport"); sport.setLanguage("DE"); NewsMetaCategory soccer = new NewsMetaCategory(); soccer.setFs_id(3l); soccer.setLanguage("DE"); soccer.setName("Fussball"); if (sport.getMetaCategories() == null) { sport.setMetaCategories(new ArrayList<NewsMetaCategory>()); } sport.getMetaCategories().add(soccer); if (news.getCategories() == null) { news.setCategories(new ArrayList<NewsCategory>()); } news.getCategories().add(sport); em.persist(news); em.flush(); tx.commit(); assertEquals("Entity not filled", size + 1, countNews()); Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3"); NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult(); assertNotNull(metaCat); query = em.createQuery( "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id()); NewsCategory category = (NewsCategory) query.getSingleResult(); assertNotNull(category); query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id()); News n = (News) query.getSingleResult(); assertNotNull(n); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java
@Override public Vacancy getById(int id) { EntityManager em = entityManagerFactory.createEntityManager(); Vacancy vacancy = null;//from w ww .ja va 2s .co m try { em.getTransaction().begin(); vacancy = em.find(Vacancy.class, id); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return vacancy; }
From source file:net.anthonychaves.bookmarks.service.UserService.java
public User findUser(String emailAddress) { EntityManager em = emf.createEntityManager(); User user = null;/*from w w w . j av a2s. c o m*/ try { Query query = em.createQuery("select u from User u where u.emailAddress = ?1").setParameter(1, emailAddress); em.getTransaction().begin(); user = (User) query.getSingleResult(); em.getTransaction().rollback(); } catch (NoResultException e) { user = null; } return user; }
From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployeeRepositoryImplementation.java
@Override public boolean update(Employee employee) { EntityManager em = entityManagerFactory.createEntityManager(); boolean success = true; try {/* w w w. j a v a 2s .c o m*/ em.getTransaction().begin(); em.merge(employee); em.flush(); em.getTransaction().commit(); success = true; } catch (RuntimeException e) { Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); success = false; } em.close(); } return success; }
From source file:ejb.bean.UsuarioDAOJPAImplBean.java
/**Mtodo para a criao de usurio * @author Richel Sensineli\//from w w w. j a va 2 s . c o m * @param nome String - Nome do usurio * @param sobrenome String - Nome do usurio * @return Usuario usuario - Objeto Usurio */ @Override public Usuario criaUsuario(final String nome, final String sobrenome) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU"); EntityManager em = emf.createEntityManager(); UsuarioImpl user = new UsuarioImpl(); user.setNome(nome); user.setSobrenome(sobrenome); em.getTransaction().begin(); try { em.persist(user); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); em.getTransaction().rollback(); } em.clear(); em.close(); emf.close(); return user; }