List of usage examples for javax.persistence EntityManagerFactory createEntityManager
public EntityManager createEntityManager();
EntityManager
. From source file:be.thomasmore.controller.FileController.java
private void leesExcel() { try {/*w w w . j a v a2 s . com*/ //Excelbestand in RAM steken voor Apache POI InputStream fileInputStream = part.getInputStream(); XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream); XSSFSheet worksheet = workbook.getSheet("Blad1"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("ScoreTrackerPU"); EntityManager em = emf.createEntityManager(); //Iterator om door de worksheets te gaan (enkel nodig om het eerste worksheet door te gaan) Iterator<Row> rowIterator = worksheet.iterator(); //Klas zoeken en persisten //Door de rijen itereren while (rowIterator.hasNext()) { Row row = rowIterator.next(); //Over de kolommen van deze rij itereren Iterator<Cell> cellIterator = row.cellIterator(); if (row.getRowNum() == 0) { while (cellIterator.hasNext()) { //Cell vastnemen Cell cell = cellIterator.next(); //Kijken of er in de eerste cell 'klas' staat switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (cell.getStringCellValue().equalsIgnoreCase("klas")) { //breaken zodat hij doorgaat naar de volgende cell break; //Checken of de cell niet leeg is } else if (!cell.getStringCellValue().equalsIgnoreCase("")) { if (klas.getNummer() == null) { //Klas werkt Query q = em.createNamedQuery("Klas.findByNummer"); q.setParameter("nummer", cell.getStringCellValue()); if (q.getResultList().size() == 0) { klas.setNummer(cell.getStringCellValue()); defaultService.addKlas(klas); } else { klas = (Klas) q.getSingleResult(); } } } break; } } //Einde van celliterator } else if (row.getRowNum() == 1) { while (cellIterator.hasNext()) { //Cell vastnemen Cell cell = cellIterator.next(); //Kijken of in de allereerste cel 'vak' staat switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: if (cell.getStringCellValue().equalsIgnoreCase("vak")) { //breaken zodat hij doorgaat naar de volgende cell break; } else if (!cell.getStringCellValue().equalsIgnoreCase("")) { if (vak.getNaam() == null) { Query q = em.createNamedQuery("Vak.findByNaam"); q.setParameter("naam", cell.getStringCellValue()); if (q.getResultList().size() == 0) { vak.setNaam(cell.getStringCellValue()); defaultService.addVak(vak); } else { vak = (Vak) q.getSingleResult(); } } } } } //Einde van celliterator } else if (row.getRowNum() == 2) { while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (cell.getColumnIndex() == 1) { test.setBeschrijving(cell.getStringCellValue()); } } } else if (row.getRowNum() == 3) { while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().equalsIgnoreCase("totaal")) { } if (cell.getColumnIndex() == 1) { test.setTotaalScore((int) cell.getNumericCellValue()); test.setVakId(vak); /// Query q = em.createNamedQuery("Test.findByBeschrijving"); q.setParameter("beschrijving", test.getBeschrijving()); if (q.getResultList().size() == 0) { defaultService.addTest(test); } else { test = (Test) q.getSingleResult(); } /// klasTest.setKlasId(klas); klasTest.setTestId(test); Query q2 = em.createNamedQuery("Klastest.findByKlasIdTestId"); q2.setParameter("klasId", klasTest.getKlasId()); q2.setParameter("testId", klasTest.getTestId()); if (q2.getResultList().size() == 0) { if (klasTest.getKlasId().getId() != null) { defaultService.addKlastest(klasTest); } } else { klasTest = (Klastest) q2.getSingleResult(); } } } } else if (row.getRowNum() > 5) { Student student = new Student(); Score score = new Score(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().equalsIgnoreCase("zit al in de DB")) { break; } if (cell.getColumnIndex() == 0) { if (cell.getCellType() != Cell.CELL_TYPE_BLANK) { student.setStudentenNr((int) cell.getNumericCellValue()); } } if (cell.getColumnIndex() == 1) { String[] voorenachternaam = cell.getStringCellValue().split("\\s+"); student.setVoornaam(voorenachternaam[0]); if (voorenachternaam.length >= 3) { if (voorenachternaam.length >= 4) { student.setNaam( voorenachternaam[1] + voorenachternaam[2] + voorenachternaam[3]); student.setEmail(voorenachternaam[0] + "." + voorenachternaam[1] + voorenachternaam[2] + voorenachternaam[3] + "@student.thomasmore.be"); } else { student.setNaam(voorenachternaam[1] + voorenachternaam[2]); student.setEmail(voorenachternaam[0] + "." + voorenachternaam[1] + voorenachternaam[2] + "@student.thomasmore.be"); } } else { student.setNaam(voorenachternaam[1]); student.setEmail( voorenachternaam[0] + "." + voorenachternaam[1] + "@student.thomasmore.be"); } student.setKlasId(klas); } if (cell.getColumnIndex() == 2) { score.setScore((int) cell.getNumericCellValue()); score.setTestId(test); score.setStudentId(student); break; } } if (student.getStudentenNr() != null) { studenten.add(student); } if (score.getTestId() != null && score.getStudentId().getStudentenNr() != null) { scores.add(score); } } } //einde van rowiterator for (Student student : studenten) { Query q = em.createNamedQuery("Student.findByStudentenNr"); q.setParameter("studentenNr", student.getStudentenNr()); if (q.getResultList().size() == 0) { defaultService.addStudent(student); } else { Student st = (Student) q.getSingleResult(); student.setId(st.getId()); } } for (Score score : scores) { Query q = em.createNamedQuery("Score.findByTestIdStudentIdScore"); q.setParameter("testId", score.getTestId()); q.setParameter("studentId", score.getStudentId()); q.setParameter("score", score.getScore()); if (q.getResultList().size() == 0) { defaultService.addScore(score); } else { score = (Score) q.getSingleResult(); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java
/** * Creates a new EntityManager using <tt>emf</tt>. * * <p>Calls {@link #loadConfigletStates(javax.persistence.EntityManager)} and * {@link #createOrUpdateConfiglets(de.zib.gndms.model.common.ConfigletState[])} to load all configlets managed by * this EntityManager and update the {@link #configlets} map. * Old Configlets will be removed and shutted down using {@link #shutdownConfiglets()} * * @param emf the factory the EntityManager will be created of *//* ww w .j ava 2 s. c om*/ public synchronized void reloadConfiglets(final EntityManagerFactory emf) { ConfigletState[] states; EntityManager em = emf.createEntityManager(); try { states = loadConfigletStates(em); createOrUpdateConfiglets(states); shutdownOldConfiglets(em); } finally { if (em.isOpen()) em.close(); } }
From source file:corner.orm.gae.impl.EntityManagerSourceImpl.java
public EntityManagerSourceImpl(@Inject @Symbol(SymbolConstants.PRODUCTION_MODE) boolean product, EntityManagerFactory entityManagerFactory, Logger logger, Delegate delegate) { this.entityManagerFactory = entityManagerFactory; this.logger = logger; if (!product) { ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment()); ApiProxy.setDelegate(delegate);//from ww w .ja va 2s . co m } if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) { // Do not modify the Session: just set the participate flag. participate = true; } else { logger.debug("Opening single entity manager in EntityManagerSourceImpl"); EntityManager em = entityManagerFactory.createEntityManager(); TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(em)); } }
From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java
private EntityManager initEmpireEM(File config, File annox, String pack) { System.setProperty("empire.configuration.file", config.getPath()); EmpireConfiguration ecfg = new EmpireConfiguration(); ecfg.getGlobalConfig().put(ConfigKeys.ANNOTATION_INDEX, annox.getPath()); Empire.init(ecfg, new OpenRdfEmpireModule()); EmpireOptions.STRICT_MODE = false;//from w w w . j a va 2s . c o m PersistenceProvider aProvider = Empire.get().persistenceProvider(); EntityManagerFactory emf = aProvider.createEntityManagerFactory(pack, getTestEMConfigMap()); EntityManager em = emf.createEntityManager(); return em; }
From source file:org.batoo.jpa.benchmark.BenchmarkTest.java
private EntityManager open(final EntityManagerFactory emf) { final EntityManager em = emf.createEntityManager(); em.getTransaction().begin();/*from ww w.j a va 2 s . co m*/ return em; }
From source file:org.debux.webmotion.jpa.Transactional.java
/** * Create the transaction and the GenericDAO if the entity name is not * empty or null.//from www . j ava 2 s . co m * * @param request set EntityManager, EntityTransaction and GenericDAO into the request * @param persistenceUnitName precise the persistence unit * @param packageEntityName precise the package of entity * @param entityName precise the class name of the entity * * @throws Exception catch execption to rollback the transaction */ public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties, String packageEntityName, String entityName) throws Exception { // Create factory if (persistenceUnitName == null || persistenceUnitName.isEmpty()) { persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME; } EntityManagerFactory factory = factories.get(persistenceUnitName); if (factory == null) { Configuration subset = properties.subset(persistenceUnitName); java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset); factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties); factories.put(persistenceUnitName, factory); } // Create manager EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER); if (manager == null) { manager = factory.createEntityManager(); request.setAttribute(CURRENT_ENTITY_MANAGER, manager); } // Create generic DAO each time if callback an action on an other entity if (entityName != null) { String fullEntityName = null; if (packageEntityName != null && !packageEntityName.isEmpty()) { fullEntityName = packageEntityName + "." + entityName; } else { fullEntityName = entityName; } GenericDAO genericDAO = new GenericDAO(manager, fullEntityName); request.setAttribute(CURRENT_GENERIC_DAO, genericDAO); } else { request.setAttribute(CURRENT_GENERIC_DAO, null); } // Create transaction EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION); if (transaction == null) { transaction = manager.getTransaction(); request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction); transaction.begin(); try { doProcess(); } catch (Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw e; } if (transaction.isActive()) { transaction.commit(); } manager.close(); } else { doProcess(); } }
From source file:servlet.itemdescription.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j a va2s. c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // location to store file uploaded final String UPLOAD_DIRECTORY = "upload"; // upload settings final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB //---------------------------------------------------------------------- //response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); EntityManagerFactory emf = null; EntityManager em = null; try { emf = Persistence.createEntityManagerFactory(cons.entityName); em = emf.createEntityManager(); ItemDescriptionJpaController controller = new ItemDescriptionJpaController(emf); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { String id = ""; String code = ""; String description = ""; String itemType = ""; String fileName = ""; String unitId = ""; String generId = ""; String operation = ""; //------------------------------------------------------------------------------------------------------------------------------------- // File upload try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory // String uploadPath = getServletContext().getRealPath("") // + File.separator + UPLOAD_DIRECTORY; String uploadPath = "E:\\insiderUploads"; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } // Parse the request List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { //These are form fields String fieldName = item.getFieldName(); String fieldValue = item.getString(); if (fieldName.equalsIgnoreCase("honga")) { operation = request.getParameter("honga"); System.out.println("operation: " + operation); } else if (fieldName.equalsIgnoreCase("operation")) { operation = request.getParameter("operation"); System.out.println("operation: " + operation); } //----------------- Check Add Fields ------------------------- else if (fieldName.equalsIgnoreCase("id")) { id = request.getParameter("id"); System.out.println("id " + id); } else if (fieldName.equalsIgnoreCase("code")) { code = fieldValue; System.out.println("code " + code); } else if (fieldName.equalsIgnoreCase("description")) { description = fieldValue; System.out.println("description: " + description); } else if (fieldName.equalsIgnoreCase("item_type")) { itemType = fieldValue; System.out.println("item_type: " + itemType); } else if (fieldName.equalsIgnoreCase("unit_id")) { unitId = fieldValue; System.out.println("unit_id: " + itemType); } if (fieldName.equalsIgnoreCase("gener_id")) { generId = fieldValue; System.out.println("Genre: " + generId); } //----------------- Check Edit Fields ------------------------ else if (fieldName.equalsIgnoreCase("editItemDescriptionId")) { id = request.getParameter("editItemDescriptionId"); System.out.println("editItemDescriptionId: " + id); } else if (fieldName.equalsIgnoreCase("editItemCode")) { code = fieldValue; System.out.println("editItemCode " + code); } else if (fieldName.equalsIgnoreCase("editDescription")) { description = fieldValue; System.out.println("editDescription: " + description); } else if (fieldName.equalsIgnoreCase("editItemType")) { itemType = fieldValue; System.out.println("editItemType: " + itemType); } else if (fieldName.equalsIgnoreCase("editUnitId")) { unitId = fieldValue; System.out.println("editUnitId: " + itemType); } if (fieldName.equalsIgnoreCase("generId")) { generId = fieldValue; System.out.println("generId: " + generId); } } else // This is a file { fileName = item.getName(); System.out.println("FILE NAME: " + fileName); if (fileName != null && !fileName.isEmpty()) { String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("message", "Upload has been done successfully!"); out.println("File Name: " + fileName); } else { continue; } } } // add the item to the database // if (operation.equalsIgnoreCase("add")) { em.getTransaction().begin(); ItemDescription itemDescription = new ItemDescription(); if (code != null) { itemDescription.setItemCode(new Integer(code)); } itemDescription.setItemDesc(description); itemDescription.setItemTypeId(new Integer(itemType)); itemDescription.setUnitId(new Integer(unitId)); itemDescription.setGenerId(new Integer(generId)); // itemDescription.setUpload(request.getParameter("file").getBytes()); itemDescription.setUploadFileName(fileName); controller.create(itemDescription); em.getTransaction().commit(); // } else if (operation.equalsIgnoreCase("edit")) { // em.getTransaction().begin(); // ItemDescription itemDescription = new ItemDescription(); // if (code != null) { // itemDescription.setItemCode(new Integer(code)); // } // // itemDescription.setItemDesc(description); // itemDescription.setItemTypeId(new Integer(itemType)); // itemDescription.setUnitId(new Integer(unitId)); // itemDescription.setGenerId(new Integer(generId)); //// itemDescription.setUpload(request.getParameter("file").getBytes()); // controller.edit(itemDescription); // em.getTransaction().commit(); // } response.sendRedirect("itemdesc.jsp"); } catch (FileUploadException ex) { Logger.getLogger(itemdescription.class.getName()).log(Level.SEVERE, null, ex); } //------------------------------------------------------------------------------------------------------------------------------------- } else if (request.getParameter("operation") != null && !request.getParameter("operation").isEmpty()) { String id = ""; String code = ""; String description = ""; String itemType = ""; String fileName = ""; String unitId = ""; String generId = ""; String operation = request.getParameter("operation"); String operationId = request.getParameter("operationId"); response.setContentType("application/json"); if (operation.equalsIgnoreCase("edit")) { //This is update operation System.out.println("UPDATE OPERATION"); operationId = request.getParameter("editItemDescriptionId"); code = request.getParameter("editItemCode"); description = request.getParameter("editDescription"); itemType = request.getParameter("editItemType"); unitId = request.getParameter("editUnitId"); generId = request.getParameter("generId"); System.out.println("Item ID: " + operationId + "Item Code: " + code + " | Desc: " + description + " | Item type: " + itemType + " | UnitId: " + unitId + " | Genre Id: " + generId); ItemDescription itemDescription = controller.findItemDescription(new Integer(operationId)); if (code != null) { itemDescription.setItemCode(new Integer(code)); } em.getTransaction().begin(); itemDescription.setItemDesc(description); itemDescription.setItemTypeId(new Integer(itemType)); itemDescription.setUnitId(new Integer(unitId)); itemDescription.setGenerId(new Integer(generId)); // itemDescription.setUpload(request.getParameter("file").getBytes()); controller.edit(itemDescription); em.getTransaction().commit(); response.sendRedirect("itemdesc.jsp"); } else if (operation.equalsIgnoreCase("delete")) {//This is delete operation System.out.println("DELETE OPERATION"); controller.destroy(new Integer(operationId)); ItemDescription item = controller.findItemDescription(new Integer(operationId)); if (item == null) {//Item is deleted from the database System.out.println("RECORD has been deleted"); out.print(convertMessageIntoJSON( new CustomMessage(100, "Record has been deleted successfully"))); } else {//couldn't delete item System.out.println("COULDN'T DELETE RECORD"); out.print(convertMessageIntoJSON(new CustomMessage(0, "Error, couldn't delete record"))); } } else if (operation.equalsIgnoreCase("showItemDescriptionDetails")) { int itemDescriptionId = Integer.parseInt(request.getParameter("operationId")); ItemDescription itemDescription = controller.findItemDescription(itemDescriptionId); if (itemDescription == null) {//Record not found out.print(JSONUtils .convertMessageIntoJSON(new dto.CustomMessage(404, "Error, No Such record!"))); } else {//Record found out.print(JSONUtils.convertItemDescriptionIntoJSON(ItemDescriptionWrapper .getItemDescriptionWrapper(100, "Record found successfully", itemDescription))); } } } else if (request.getParameter("save") != null) { em.getTransaction().begin(); ItemDescription id = new ItemDescription(); id.setItemCode(new Integer(request.getParameter("item_code"))); id.setItemDesc(request.getParameter("item_desc")); id.setItemTypeId(new Integer(request.getParameter("item_type_id"))); id.setUnitId(new Integer(request.getParameter("unit_id"))); id.setGenerId(new Integer(request.getParameter("gener_id"))); id.setUpload(request.getParameter("file").getBytes()); controller.create(id); em.getTransaction().commit(); response.sendRedirect("itemdesc.jsp"); } else if (request.getParameter("update") != null) { em.getTransaction().begin(); ItemDescription id = new ItemDescription(); id = controller.findItemDescription(new Integer(request.getParameter("edit_material_id").trim())); id.setItemCode(new Integer(request.getParameter("item_code"))); id.setItemDesc(request.getParameter("item_desc")); id.setItemTypeId(new Integer(request.getParameter("item_type_id"))); id.setUnitId(new Integer(request.getParameter("unit_id"))); id.setGenerId(new Integer(request.getParameter("gener_id"))); id.setUpload(request.getParameter("file").getBytes()); controller.edit(id); em.getTransaction().commit(); response.sendRedirect("itemdesc.jsp"); } else if (request.getParameter("del_item") != null) { if (request.getParameter("id_value_del").trim() != null) { em.getTransaction().begin(); controller.destroy(new Integer(request.getParameter("id_value_del").trim())); em.getTransaction().commit(); response.sendRedirect("itemdesc.jsp"); } } // request.setAttribute("generlist",findGenerEntities); // request.getRequestDispatcher("/gener.jsp").forward(request, response); } catch (Exception ex) { Logger.getLogger(itemdescription.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); em.close(); emf.close(); } }
From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java
@SuppressWarnings({ "MethodWithTooExceptionsDeclared", "OverloadedMethodsWithSameNumberOfParameters" }) public TaskAction newTaskAction(final @NotNull EntityManagerFactory emf, final @NotNull String offerTypeKey) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { EntityManager em = emf.createEntityManager(); try {/* ww w. ja v a2 s . co m*/ return newTaskAction(em, offerTypeKey); } finally { if (!em.isOpen()) em.close(); } }
From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java
@SuppressWarnings({ "MethodWithTooExceptionsDeclared" }) @NotNull// w w w.ja va2 s .c o m public AbstractORQCalculator<?, ?> newORQCalculator(final @NotNull EntityManagerFactory emf, final @NotNull String offerTypeKey) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { EntityManager em = emf.createEntityManager(); try { OfferType type = em.find(OfferType.class, offerTypeKey); if (type == null) throw new IllegalArgumentException("Unknow offer type: " + offerTypeKey); AbstractORQCalculator<?, ?> orqc = orqPark.getInstance(type); orqc.setConfigletProvider(this); return orqc; } finally { if (!em.isOpen()) em.close(); } }
From source file:desktop.olayinka.file.transfer.model.DerbyJDBCHelper.java
private DerbyJDBCHelper() { try {/*from w w w . j a va 2 s .c om*/ System.out.println(DB_URL); //ensure database is created String dbUrl = "jdbc:derby:" + DB_FILE.getAbsolutePath() + ";create=true;user=" + DB_USER + ";password=" + DB_PWD; System.out.println(dbUrl); Connection mConnection; try { Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance(); mConnection = DriverManager.getConnection(dbUrl); } catch (Exception e) { e.printStackTrace(); System.exit(1); return; } onStart(mConnection); onUpgrade(mConnection); mConnection.commit(); mConnection.close(); //instantiate persistence unit EntityManagerFactory managerFactory = null; Map<String, String> persistenceMap = new HashMap<String, String>(); persistenceMap.put("javax.persistence.jdbc.url", DB_URL); persistenceMap.put("javax.persistence.jdbc.user", DB_USER); persistenceMap.put("javax.persistence.jdbc.password", DB_PWD); URL resource = ClassLoader.getSystemResource(""); File file = new File(String.valueOf(resource)); managerFactory = Persistence.createEntityManagerFactory("A2PPU", persistenceMap); mManager = managerFactory.createEntityManager(); deviceProvider = new JDBCDeviceProvider(mManager); } catch (Exception except) { except.printStackTrace(); System.exit(1); } }