Java Code Examples for javax.persistence.TypedQuery#getSingleResult()

The following examples show how to use javax.persistence.TypedQuery#getSingleResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShareFacadeTest.java    From aws-photosharing-example with Apache License 2.0 6 votes vote down vote up
private Role createRole() {
    Role role = new Role();
    role.setRole(ADMINISTRATOR);

    TypedQuery<Role> query =_em.createQuery("select r from Role r where r.role=:roleName", Role.class);

    query.setParameter("roleName", ADMINISTRATOR);
    Role tmpRole = null;

    try {
        tmpRole = query.getSingleResult();
    }

    catch (javax.persistence.NoResultException exc) {
        exc.printStackTrace();
    }

    if (tmpRole != null)
        role = tmpRole;

    return role;
}
 
Example 2
Source File: ContentFacadeTest.java    From aws-photosharing-example with Apache License 2.0 6 votes vote down vote up
@AfterClass
public void cleanUp() {

    // Delete S3 bucket
    DeleteBucketRequest deleteBucketRequest = new DeleteBucketRequest(ContentHelper.getInstance().getConfiguredBucketName());
    s3Client.deleteBucket(deleteBucketRequest);

    EntityManager _em = Persistence.createEntityManager();
    TypedQuery<User> query =_em.createQuery("select u from User u where u.userName=:userName", User.class);

    query.setParameter("userName", _user.getUserName());
    _user = query.getSingleResult();

    query.setParameter("userName", sharedUser.getUserName());
    sharedUser = query.getSingleResult();

    _em.getTransaction().begin();
    _em.remove(_user);
    _em.remove(sharedUser);
    _em.getTransaction().commit();
}
 
Example 3
Source File: AbstractApplyCustomScripsTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
@Cleanup
public void test2() {
    final TypedQuery<Depositor> query = manager.createQuery("SELECT d FROM Depositor d WHERE d.name='Max'", Depositor.class);
    final Depositor entity = query.getSingleResult();

    assertNotNull(entity);
    assertThat(entity.getName(), equalTo("Max"));
    assertThat(entity.getSurname(), equalTo("Payne"));

    final Set<Account> accounts = entity.getAccounts();
    assertThat(accounts.size(), equalTo(1));
    final Account account = accounts.iterator().next();
    assertThat(account, instanceOf(GiroAccount.class));
    final GiroAccount giroAccount = (GiroAccount) account;
    assertThat(giroAccount.getBalance(), equalTo(95000.0));
    assertThat(giroAccount.getCreditLimit(), equalTo(100000.0));
}
 
Example 4
Source File: UserPointsDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
public UserPoints getUserPoints(String userId, long campaignId) {
	final EntityManager em = emProvider.get();
	TypedQuery<UserPoints> query = em.createNamedQuery(DBQueries.GET_USER_POINTS, UserPoints.class);

	query.setParameter("userId", userId); //$NON-NLS-1$
	query.setParameter("campaignId", campaignId); //$NON-NLS-1$
	UserPoints result = null;
	try {
		result = query.getSingleResult();
	} catch (NoResultException x) {
		logger.debug("Could not retrieve user points for userId {} from table {}.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException e) {
		throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId)); //$NON-NLS-1$
	}
	return result;
}
 
Example 5
Source File: SectionEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<Section> findByIdQuery = em.createQuery("SELECT DISTINCT s FROM Section s LEFT JOIN FETCH s.venue WHERE s.id = :entityId ORDER BY s.id", Section.class);
   findByIdQuery.setParameter("entityId", id);
   Section entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   SectionDTO dto = new SectionDTO(entity);
   return Response.ok(dto).build();
}
 
Example 6
Source File: MediaItemEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<MediaItem> findByIdQuery = em.createQuery("SELECT DISTINCT m FROM MediaItem m WHERE m.id = :entityId ORDER BY m.id", MediaItem.class);
   findByIdQuery.setParameter("entityId", id);
   MediaItem entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   MediaItemDTO dto = new MediaItemDTO(entity);
   return Response.ok(dto).build();
}
 
Example 7
Source File: ProductDB.java    From MusicStore with MIT License 6 votes vote down vote up
/**
 * Retrieves a single product from the database, based on the provided
 * product code. 
 * @param productCode The code of the product to be retrieved
 * @return The selected product if exists, null otherwise
 */
public static Product selectProduct(String productCode) {
   EntityManager em = DBUtil.getEmFactory().createEntityManager();
   String queryString = "SELECT p FROM Product p "
                      + "WHERE p.code = :code";
   TypedQuery<Product> query = em.createQuery(queryString, Product.class);
   query.setParameter("code", productCode);
   
   Product product = null;
   try {
      product = query.getSingleResult();
   } catch (Exception e) {
      System.err.println(e);
   } finally {
      em.close();
   }
   
   return product;
}
 
Example 8
Source File: JPAUserDAO.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public User findByToken(final String token) {
    TypedQuery<User> query = entityManager().createQuery(
            "SELECT e FROM " + anyUtils().anyClass().getSimpleName()
            + " e WHERE e.token LIKE :token", User.class);
    query.setParameter("token", token);

    User result = null;
    try {
        result = query.getSingleResult();
    } catch (NoResultException e) {
        LOG.debug("No user found with token {}", token, e);
    }

    return result;
}
 
Example 9
Source File: PerformanceEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, PerformanceDTO dto)
{
   TypedQuery<Performance> findByIdQuery = em.createQuery("SELECT DISTINCT p FROM Performance p LEFT JOIN FETCH p.show WHERE p.id = :entityId ORDER BY p.id", Performance.class);
   findByIdQuery.setParameter("entityId", id);
   Performance entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   entity = dto.fromDTO(entity, em);
   try
   {
      entity = em.merge(entity);
   }
   catch (OptimisticLockException e)
   {
      return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
   }
   return Response.noContent().build();
}
 
Example 10
Source File: DocumentTypeDAOJpa.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Override
public Integer getMaxVersionNumber(String docTypeName) {
       TypedQuery<Integer> query = getEntityManager().
               createNamedQuery("DocumentType.GetMaxVersionNumber", Integer.class);
       query.setParameter("docTypeName", docTypeName);
       return query.getSingleResult();
}
 
Example 11
Source File: App.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
private void read(Long id) {
    System.out.println("--------------------- read --------------------");
    TypedQuery<Task> query = em.createNamedQuery("Task.findById", Task.class);
    query.setParameter("id", id);

    //With TypedQuery you don't need a cast to Task type below
    try {
        Task task = query.getSingleResult();
        System.out.println("task found " + task);
    } catch (NoResultException nre) {
        System.out.println("task not found ");
    }

}
 
Example 12
Source File: UserDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 5 votes vote down vote up
public User getByUserId(String userId) {
	final EntityManager em = emProvider.get();
	try {
		final TypedQuery<User> query = em.createNamedQuery(DBQueries.GET_USER_BY_USER_ID, User.class);
		query.setParameter("userId", userId); //$NON-NLS-1$
		User user = query.getSingleResult();
		return user;
	} catch (NoResultException x) {
		logger.warn("Could not retrieve entity for userId {} from table {}. Maybe the user doesn't exist yet.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException ex) {
		throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId), ex); //$NON-NLS-1$
	}

	return null;
}
 
Example 13
Source File: VmQuotaOperator.java    From zstack with Apache License 2.0 5 votes vote down vote up
private long getDataVolumeSizeAsked(APICreateDataVolumeMsg msg) {
    if (msg.getDiskOfferingUuid() == null) {
        return msg.getDiskSize();
    }

    String sql = "select diskSize from DiskOfferingVO where uuid = :uuid ";
    TypedQuery<Long> dq = dbf.getEntityManager().createQuery(sql, Long.class);
    dq.setParameter("uuid", msg.getDiskOfferingUuid());
    Long dsize = dq.getSingleResult();
    dsize = dsize == null ? 0 : dsize;
    return dsize;
}
 
Example 14
Source File: LoginDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Override
public Tblstudentuser getStudentUser(Login login) {
	String qlString = "SELECT b FROM Tblstudentuser b WHERE b.username = ?1";
	TypedQuery<Tblstudentuser> query = entityManagerFactory.createQuery(qlString, Tblstudentuser.class);
	query.setParameter(1, login.getUserName());
	return query.getSingleResult();
  
}
 
Example 15
Source File: UserEJB.java    From Tutorials with Apache License 2.0 5 votes vote down vote up
public User findUserById(String id) {
	TypedQuery<User> query = em.createNamedQuery("findUserById", User.class);
	query.setParameter("email", id);
	User user = null;
	try {
		user = query.getSingleResult();
	} catch (Exception e) {
		// getSingleResult throws NoResultException in case there is no user in DB
		// ignore exception and return NULL for user instead
	}
	return user;
}
 
Example 16
Source File: TagApiInterceptor.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private void checkAccountForUserTag(APIDeleteTagMsg msg) {
    String sql = "select ref.accountUuid from UserTagVO tag, AccountResourceRefVO ref where tag.resourceUuid = ref.resourceUuid and tag.uuid = :tuuid";
    TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
    q.setParameter("tuuid", msg.getUuid());
    String accountUuid = q.getSingleResult();
    if (!msg.getSession().getAccountUuid().equals(accountUuid)) {
        throw new ApiMessageInterceptionException(err(IdentityErrors.PERMISSION_DENIED,
                "permission denied. The user tag[uuid: %s] refer to a resource not belonging to the account[uuid: %s]",
                msg.getUuid(), msg.getSession().getAccountUuid()
        ));
    }
}
 
Example 17
Source File: PresentationEmployeeRepository.java    From batchers with Apache License 2.0 4 votes vote down vote up
public EmployeeTo getEmployee(long id) {
    TypedQuery<EmployeeTo> employees = entityManager.createQuery(GET_EMPLOYEE_DETAIL_QUERY, EmployeeTo.class);
    employees.setParameter("id", id);
    return employees.getSingleResult();
}
 
Example 18
Source File: OAuth2Dao.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
@Override
public long count() {
	TypedQuery<Long> q = em.createNamedQuery("countOAuthServers", Long.class);
	return q.getSingleResult();
}
 
Example 19
Source File: UserDao.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
@Override
public long count() {
	// get all users
	TypedQuery<Long> q = em.createNamedQuery("countNondeletedUsers", Long.class);
	return q.getSingleResult();
}
 
Example 20
Source File: JpaSql.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 4 votes vote down vote up
public UserEntity getFirst() {
    TypedQuery<UserEntity> q = em.createQuery(
            "select * from Users",
            UserEntity.class);
    return q.getSingleResult();
}