Java Code Examples for javax.persistence.EntityManager

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project arquillian-showcase, under directory /spring/spring-jpa/src/main/java/com/acme/spring/jpa/repository/impl/.

Source file: JpaStockRepository.java

  18 
vote

/** 
 * {@inheritDoc}
 */
@Override public void update(Stock stock){
  validateNoNull(stock,"stock");
  validateNotEmpty(stock.getSymbol(),"symbol");
  EntityManager entityManager=getEntityManager();
  try {
    entityManager.getTransaction().begin();
    entityManager.merge(stock);
    entityManager.getTransaction().commit();
  }
 catch (  PersistenceException exc) {
    entityManager.getTransaction().rollback();
    throw exc;
  }
}
 

Example 2

From project ATHENA, under directory /core/apa/src/main/java/org/fracturedatlas/athena/apa/impl/jpa/.

Source file: JpaApaAdapter.java

  18 
vote

@Override public Set<String> getTypes(){
  EntityManager em=this.emf.createEntityManager();
  Set<String> types=new HashSet<String>();
  try {
    Query query=em.createQuery("SELECT DISTINCT t.type FROM JpaRecord t");
    List<String> values=query.getResultList();
    logger.debug("PropValues are " + values.toString());
    types.addAll(values);
    return types;
  }
  finally {
    cleanup(em);
  }
}
 

Example 3

From project capedwarf-green, under directory /jpa/src/test/java/org/jboss/test/capedwarf/jpa/test/.

Source file: ProxyingTestCase.java

  18 
vote

@Test public void testGet() throws Exception {
  EntityManagerFactory emf=new ProxyingEntityManagerFactory(new MockEMF());
  EntityManager em=emf.createEntityManager();
  Person person=new Person();
  person.setId(1l);
  person.setName("Ales");
  em.persist(person);
  Food food=new Food();
  food.setPersonId(1l);
  food.setDescription("Pizza");
  food=em.merge(food);
  Person lazy=food.getPerson();
  Assert.assertSame(person,lazy);
}
 

Example 4

From project CMM-data-grabber, under directory /eccles/src/main/java/au/edu/uq/cmm/eccles/.

Source file: EcclesFacilityMapper.java

  18 
vote

@Override public Collection<FacilityConfig> allFacilities(){
  EntityManager em=emf.createEntityManager();
  try {
    TypedQuery<EcclesFacility> query=em.createQuery("from EcclesFacility",EcclesFacility.class);
    return new ArrayList<FacilityConfig>(query.getResultList());
  }
  finally {
    em.close();
  }
}
 

Example 5

From project dev-examples, under directory /iteration-demo/src/main/java/org/richfaces/demo/.

Source file: PersistenceService.java

  18 
vote

public EntityManager getEntityManager(){
  Map<Object,Object> attributes=FacesContext.getCurrentInstance().getAttributes();
  EntityManager manager=(EntityManager)attributes.get(PersistenceService.class);
  if (manager == null) {
    manager=entityManagerFactory.createEntityManager();
    attributes.put(PersistenceService.class,manager);
    manager.getTransaction().begin();
  }
  return manager;
}
 

Example 6

From project drools-chance, under directory /drools-informer/human-task-helpers/src/main/java/org/jbpm/task/.

Source file: TaskHelper.java

  18 
vote

public static User addUser(String id){
  EntityManagerFactory emf=Persistence.createEntityManagerFactory("org.jbpm.task");
  EntityManager em=emf.createEntityManager();
  User user=findUser(id,em);
  if (user == null) {
    user=new User(id);
    em.persist(user);
  }
  em.close();
  emf.close();
  return user;
}
 

Example 7

From project droolsjbpm-integration, under directory /drools-container/drools-spring/src/main/java/org/drools/container/spring/beans/persistence/.

Source file: DroolsSpringJpaManager.java

  18 
vote

public void clearPersistenceContext(){
  if (TransactionSynchronizationManager.hasResource("cmdEM")) {
    EntityManager cmdScopedEntityManager=(EntityManager)this.env.get(EnvironmentName.CMD_SCOPED_ENTITY_MANAGER);
    if (cmdScopedEntityManager != null) {
      cmdScopedEntityManager.clear();
    }
  }
}
 

Example 8

From project Empire, under directory /core/src/com/clarkparsia/empire/impl/.

Source file: EntityManagerFactoryImpl.java

  18 
vote

/** 
 * @inheritDoc
 */
public EntityManager createEntityManager(final Map theMap){
  assertOpen();
  EntityManager aManager=newEntityManager(theMap);
  mManagers.add(aManager);
  return aManager;
}
 

Example 9

From project exo-training, under directory /gxt-showcase/src/main/java/com/sencha/gxt/examples/resources/server/data/.

Source file: Folder.java

  18 
vote

public static Folder findFolder(Integer id){
  if (id == null) {
    return null;
  }
  EntityManager em=entityManager();
  Folder session=em.find(Folder.class,id);
  return session;
}
 

Example 10

From project framework, under directory /impl/extension/jpa/src/main/java/br/gov/frameworkdemoiselle/internal/producer/.

Source file: EntityManagerProducer.java

  18 
vote

public EntityManager getEntityManager(String persistenceUnit){
  EntityManager entityManager=null;
  if (cache.containsKey(persistenceUnit)) {
    entityManager=cache.get(persistenceUnit);
  }
 else {
    entityManager=factory.create(persistenceUnit).createEntityManager();
    entityManager.setFlushMode(FlushModeType.AUTO);
    cache.put(persistenceUnit,entityManager);
    this.logger.info(bundle.getString("entity-manager-was-created",persistenceUnit));
  }
  return entityManager;
}
 

Example 11

From project capedwarf-blue, under directory /testsuite/src/test/java/org/jboss/test/capedwarf/testsuite/jpa/test/.

Source file: AbstractJPATest.java

  17 
vote

protected <T>T run(EMAction<T> action,final boolean useTx) throws Throwable {
  final EntityManager em=getEMF().createEntityManager();
  try {
    EntityTransaction tx=null;
    if (useTx)     tx=em.getTransaction();
    try {
      if (useTx)       tx.begin();
      return action.go(em);
    }
 catch (    Throwable t) {
      if (useTx)       tx.setRollbackOnly();
      throw t;
    }
 finally {
      if (useTx) {
        if (tx.getRollbackOnly())         tx.rollback();
 else         tx.commit();
      }
    }
  }
  finally {
    em.close();
  }
}
 

Example 12

From project eucalyptus, under directory /clc/modules/axis2-transport/src/edu/ucsb/eucalyptus/transport/auth/.

Source file: UserAuthentication.java

  17 
vote

public EucalyptusMessage authenticate(final X509Certificate cert,final EucalyptusMessage msg) throws EucalyptusCloudException {
  try {
    return super.authenticate(cert,msg);
  }
 catch (  EucalyptusCloudException e) {
    AbstractKeyStore userKs=UserKeyStore.getInstance();
    String userAlias=null;
    try {
      userAlias=userKs.getCertificateAlias(cert);
    }
 catch (    GeneralSecurityException ex) {
      throw new EucalyptusCloudException(ex);
    }
    EntityManager em=EntityWrapper.getEntityManagerFactory(EucalyptusProperties.NAME).createEntityManager();
    Session session=(Session)em.getDelegate();
    UserInfo searchUser=new UserInfo();
    CertificateInfo searchCert=new CertificateInfo();
    searchCert.setCertAlias(userAlias);
    Example qbeUser=Example.create(searchUser).enableLike(MatchMode.EXACT);
    Example qbeCert=Example.create(searchCert).enableLike(MatchMode.EXACT);
    List<UserInfo> users=(List<UserInfo>)session.createCriteria(UserInfo.class).add(qbeUser).createCriteria("certificates").add(qbeCert).list();
    if (users.size() > 1) {
      em.close();
      throw new EucalyptusCloudException("Certificate with more than one entities: " + userAlias);
    }
 else     if (users.size() < 1) {
      em.close();
      throw new EucalyptusCloudException("WS-Security screw up -- unauthorized user has authorized certificate: " + userAlias);
    }
 else {
      msg.setUserId(users.get(0).getUserName());
      if (users.get(0).isAdministrator())       msg.setEffectiveUserId(EucalyptusProperties.NAME);
 else       msg.setEffectiveUserId(users.get(0).getUserName());
      em.close();
    }
    return msg;
  }
}
 

Example 13

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/jpa/cache/.

Source file: FullCacheEvictionStrategy.java

  15 
vote

/** 
 * @see org.jboss.arquillian.persistence.JpaCacheEvictionStrategy#evictCache(javax.persistence.EntityManagerFactory)
 */
@Override public final void evictCache(EntityManager em){
  final Cache cache=em.getEntityManagerFactory().getCache();
  if (cache != null) {
    cache.evictAll();
  }
}
 

Example 14

From project arquillian-extension-spring, under directory /arquillian-service-integration-spring-3-int-tests/src/test/java/org/jboss/arquillian/spring/testsuite/test/.

Source file: JpaEmployeeRepositoryTestCase.java

  15 
vote

/** 
 * <p>Executes a sql script.</p>
 * @param entityManager the entity manager
 * @param fileName      the file name
 * @throws java.io.IOException if any error occurs
 */
public static void runScript(EntityManager entityManager,String fileName) throws IOException {
  InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
  BufferedReader inputReader=new BufferedReader(new InputStreamReader(input));
  StringBuilder stringBuilder=new StringBuilder();
  String line;
  while ((line=inputReader.readLine()) != null) {
    if (!line.startsWith("--")) {
      stringBuilder.append(line);
    }
  }
  String[] commands=stringBuilder.toString().split(";");
  for (  final String command : commands) {
    entityManager.createNativeQuery(command).executeUpdate();
  }
}
 

Example 15

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/ticket/registry/support/.

Source file: JpaLockingStrategy.java

  15 
vote

private boolean acquire(final EntityManager em,Lock lock){
  lock.setUniqueId(uniqueId);
  if (lockTimeout > 0) {
    final Calendar cal=Calendar.getInstance();
    cal.add(Calendar.SECOND,lockTimeout);
    lock.setExpirationDate(cal.getTime());
  }
 else {
    lock.setExpirationDate(null);
  }
  boolean success=false;
  try {
    if (lock.getApplicationId() != null) {
      lock=em.merge(lock);
    }
 else {
      lock.setApplicationId(applicationId);
      em.persist(lock);
    }
    success=true;
  }
 catch (  PersistenceException e) {
    success=false;
    if (logger.isDebugEnabled()) {
      logger.debug("{} could not obtain {} lock.",new Object[]{uniqueId,applicationId,e});
    }
 else {
      logger.info("{} could not obtain {} lock.",uniqueId,applicationId);
    }
  }
  return success;
}
 

Example 16

From project datavalve, under directory /samples/wicketDemo/src/main/java/org/fluttercode/datavalve/samples/wicketdemo/model/.

Source file: ModelBuilder.java

  15 
vote

public static void execute(EntityManager em,int count){
  log.debug("Building model database with {} rows",count);
  em.getTransaction().begin();
  try {
    for (int i=0; i < count; i++) {
      Person person=new Person();
      person.setFirstName(dataFactory.getFirstName());
      person.setLastName(dataFactory.getLastName());
      person.setPhone(dataFactory.getNumberText(10));
      em.persist(person);
      if (i % 20 == 0) {
        em.getTransaction().commit();
        em.getTransaction().begin();
      }
    }
    em.getTransaction().commit();
  }
 catch (  Exception e) {
    em.getTransaction().rollback();
  }
}