List of usage examples for javax.persistence EntityManager close
public void close();
From source file:edu.kit.dama.rest.sharing.services.impl.SharingRestServiceImpl.java
@Override public IEntityWrapper<? extends IDefaultGrant> getGrantById(Long pId, String pGroupId, HttpContext hc) { //@TODO Hack using EM directly...other way? EntityManager em = PU.entityManager(); try {/*from w w w. ja v a2s. co m*/ LOGGER.debug("Finding grant for id " + pId); Grant grant = FindUtil.findGrant(em, pId); // return RestUtils.transformObject(IMPL_CLASSES, Constants.REST_DEFAULT_OBJECT_GRAPH, new GrantWrapper(grant)); return new GrantWrapper(grant); } catch (EntityNotFoundException ex) { LOGGER.error("EntityNotFoundException caught while obtaining Grant for id " + pId + ". Probably, there is no grant for this id.", ex); throw new WebApplicationException(404); } finally { em.close(); } }
From source file:com.invariantproperties.sandbox.springentitylistener.listener.SpringEntityListenersConfigurer.java
@PostConstruct public void registerListeners() { // get registry so we can add listeners. HibernateEntityManagerFactory hemf = (HibernateEntityManagerFactory) entityManagerFactory; SessionFactory sf = hemf.getSessionFactory(); EventListenerRegistry registry = ((SessionFactoryImpl) sf).getServiceRegistry() .getService(EventListenerRegistry.class); final Set<Object> listeners = new HashSet<Object>(); EntityManager entityManager = null; try {/* w ww .j av a 2 s .c om*/ entityManager = hemf.createEntityManager(); // for every entity known to the system... for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) { // ... register event listeners for it. if (entity.getJavaType().isAnnotationPresent(SpringEntityListeners.class)) { SpringEntityListeners annotation = (SpringEntityListeners) entity.getJavaType() .getAnnotation(SpringEntityListeners.class); for (Class<?> beanClass : annotation.value()) { Map<String, ?> map = context.getBeansOfType(beanClass); listeners.addAll(map.values()); } } } } finally { if (entityManager != null) { entityManager.close(); } } // register adapter and listeners. HibernateEntityListenersAdapter adapter = new HibernateEntityListenersAdapter( new ArrayList<Object>(listeners), entityManagerFactory); registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_INSERT).appendListener(adapter); registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_UPDATE).appendListener(adapter); registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_COMMIT_DELETE).appendListener(adapter); registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(adapter); }
From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java
@Override @RequestMapping(value = "/_{subspace}/config", method = RequestMethod.PUT) @Secured("ROLE_ADMIN") public ResponseEntity<Void> setSubspaceConfiguration(@PathVariable final String subspace, @RequestBody final Configuration config, @RequestHeader("DN") final String dn) { GNDMSResponseHeader headers = getSubspaceHeaders(subspace, dn); try {//from ww w . j a va2s. co m SubspaceConfiguration subspaceConfig = SubspaceConfiguration.checkSubspaceConfig(config); if (!subspaceProvider.exists(subspace) || subspaceConfig.getMode() != SetupMode.UPDATE) { logger.warn("Subspace " + subspace + " cannot be updated"); return new ResponseEntity<Void>(null, headers, HttpStatus.FORBIDDEN); } final EntityManager em = emf.createEntityManager(); TxFrame tx = new TxFrame(em); try { SetupSubspaceAction action = new SetupSubspaceAction(subspaceConfig); action.setOwnEntityManager(em); logger.info("Calling action for updating the supspace " + subspace + "."); action.call(); } finally { tx.finish(); if (em != null && em.isOpen()) { em.close(); } } return new ResponseEntity<Void>(null, headers, HttpStatus.OK); } catch (WrongConfigurationException e) { logger.warn(e.getMessage()); return new ResponseEntity<Void>(null, headers, HttpStatus.BAD_REQUEST); } }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
public Firma findFirma(Long idFirma) { EntityManager em = null; try {/* ww w . j av a 2 s .c o m*/ em = getEntityManager(); Query q = em.createQuery( "select distinct f from Firma f left join fetch f.personasFirmaCollection where f.id=:id"); q.setParameter("id", idFirma); List<Firma> list = q.getResultList(); if (list != null && list.size() > 0) { return list.get(0); } return null; } finally { if (em != null) { em.close(); } } }
From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java
public synchronized EntityManagerFactory create(File database) throws MetadataException { EntityManagerFactory factory;// www. j a v a2 s . c om 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:org.noorganization.instalist.server.api.IngredientResource.java
/** * Creates the ingredient.//from w ww . j a va2 s.co m * @param _groupId The id of the group that will contain the ingredient. * @param _entity Data for the created ingredient. */ @POST @TokenSecured @Consumes("application/json") @Produces({ "application/json" }) public Response postIngredient(@PathParam("groupid") int _groupId, IngredientInfo _entity) throws Exception { if (_entity.getUUID() == null || _entity.getRecipeUUID() == null || _entity.getProductUUID() == null || (_entity.getDeleted() != null && _entity.getDeleted()) || (_entity.getAmount() != null && _entity.getAmount() < 0.001f)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toCreate; UUID productUUID; UUID recipeUUID; try { toCreate = UUID.fromString(_entity.getUUID()); productUUID = UUID.fromString(_entity.getProductUUID()); recipeUUID = UUID.fromString(_entity.getRecipeUUID()); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant created; if (_entity.getLastChanged() != null) { created = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(created)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else created = Instant.now(); float amount = (_entity.getAmount() != null ? _entity.getAmount() : 1f); EntityManager manager = DatabaseHelper.getInstance().getManager(); IIngredientController ingredientController = ControllerFactory.getIngredientController(manager); try { ingredientController.add(_groupId, toCreate, recipeUUID, productUUID, amount, created); } catch (ConflictException _e) { return ResponseFactory.generateConflict( new Error().withMessage("The sent data would " + "conflict with saved ingredient.")); } catch (BadRequestException _e) { return ResponseFactory.generateBadRequest( new Error().withMessage("The referenced " + "recipe or product was not found.")); } finally { manager.close(); } return ResponseFactory.generateCreated(null); }
From source file:org.noorganization.instalist.server.api.TaggedProductResource.java
/** * Creates the tagged product.// ww w.ja va 2 s .co m * @param _groupId The id of the group that will contain the tagged product. * @param _entity Data for the created tagged product. */ @POST @TokenSecured @Consumes("application/json") @Produces({ "application/json" }) public Response postTaggedProduct(@PathParam("groupid") int _groupId, TaggedProductInfo _entity) throws Exception { if (_entity.getUUID() == null || _entity.getTagUUID() == null || _entity.getProductUUID() == null || (_entity.getDeleted() != null && _entity.getDeleted())) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toCreate; UUID productUUID; UUID tagUUID; try { toCreate = UUID.fromString(_entity.getUUID()); productUUID = UUID.fromString(_entity.getProductUUID()); tagUUID = UUID.fromString(_entity.getTagUUID()); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant created; if (_entity.getLastChanged() != null) { created = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(created)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else created = Instant.now(); EntityManager manager = DatabaseHelper.getInstance().getManager(); ITaggedProductController taggedProductController = ControllerFactory.getTaggedProductController(manager); try { taggedProductController.add(_groupId, toCreate, tagUUID, productUUID, created); } catch (ConflictException _e) { return ResponseFactory.generateConflict( new Error().withMessage("The sent data would " + "conflict with saved tagged product.")); } catch (BadRequestException _e) { return ResponseFactory.generateBadRequest( new Error().withMessage("The referenced " + "recipe or tag was not found.")); } finally { manager.close(); } return ResponseFactory.generateCreated(null); }
From source file:org.noorganization.instalist.server.api.EntryResource.java
/** * Creates the listEntry.//from w w w . j a v a2 s .c om * @param _groupId The id of the group containing the entry. * @param _entity Data for created the entry. */ @POST @TokenSecured @Consumes("application/json") @Produces({ "application/json" }) public Response postEntry(@PathParam("groupid") int _groupId, EntryInfo _entity) throws Exception { if (_entity.getUUID() == null || _entity.getListUUID() == null || _entity.getProductUUID() == null || (_entity.getDeleted() != null && _entity.getDeleted()) || (_entity.getAmount() != null && _entity.getAmount() < 0.001f)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA); UUID toCreate; UUID productUUID; UUID listUUID; try { toCreate = UUID.fromString(_entity.getUUID()); productUUID = UUID.fromString(_entity.getProductUUID()); listUUID = UUID.fromString(_entity.getListUUID()); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } Instant created; if (_entity.getLastChanged() != null) { created = _entity.getLastChanged().toInstant(); if (Instant.now().isBefore(created)) return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } else created = Instant.now(); float amount = (_entity.getAmount() != null ? _entity.getAmount() : 1f); int priority = (_entity.getPriority() != null ? _entity.getPriority() : 0); boolean struck = (_entity.getStruck() != null ? _entity.getStruck() : false); EntityManager manager = DatabaseHelper.getInstance().getManager(); IEntryController entryController = ControllerFactory.getEntryController(manager); try { entryController.add(_groupId, toCreate, productUUID, listUUID, amount, priority, struck, created); } catch (ConflictException _e) { return ResponseFactory.generateConflict( new Error().withMessage("The sent data would " + "conflict with saved list entry.")); } catch (BadRequestException _e) { return ResponseFactory.generateBadRequest( new Error().withMessage("The referenced " + "product or list was not found.")); } finally { manager.close(); } return ResponseFactory.generateCreated(null); }
From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java
public Persona findPersona(Long id) { EntityManager em = null; try {/*from w w w .j a v a 2 s. c o m*/ em = getEntityManager(); Query q = em.createQuery( "select p from Persona p left join fetch p.personaTitulosCollection where p.id=:id"); q.setParameter("id", id); List<Persona> list = q.getResultList(); if (list != null && !list.isEmpty()) { return list.get(0); } else { return null; } } finally { if (em != null) { em.close(); } } }
From source file:au.edu.uq.cmm.paul.grabber.Analyser.java
private SortedSet<DatasetMetadata> buildInDatabaseMetadata() { TreeSet<DatasetMetadata> inDatabase = new TreeSet<DatasetMetadata>(ORDER_BY_BASE_PATH_AND_TIME_AND_ID); EntityManager em = emf.createEntityManager(); try {//from w ww . j a v a2s . c om TypedQuery<DatasetMetadata> query = em.createQuery( "from DatasetMetadata m left join fetch m.datafiles " + "where m.facilityName = :name", DatasetMetadata.class); query.setParameter("name", getFacility().getFacilityName()); for (DatasetMetadata ds : query.getResultList()) { if (inDatabase.add(ds)) { ds.getDatafiles().size(); } } } finally { em.close(); } return inDatabase; }