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

The following are Jave code examples for showing how to use getSingleResult() of the javax.persistence.TypedQuery class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: full-javaee-app   File: CompanyDataAccessObject.java   Source Code and License Vote up 7 votes
public static Companies getByName(String name) {
    if (name != null && !name.isEmpty()) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        String query = "SELECT company FROM Companies company where company.name = :name";
        TypedQuery<Companies> q = em.createQuery(query, Companies.class);
        q.setParameter("name", name);
        try {
            Companies company = q.getSingleResult();
            em.close();
            return company;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example 2
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 6 votes
@Test
public void test201_Insert() throws Exception {
    em.getTransaction().begin();

    Employee e = new Employee();
    e.setEmpNo(99999);
    e.setFirstName("John");
    e.setLastName("Doe");
    e.setBirthDate(DATE_FORMATTER.parse("2008-04-12"));
    e.setGender(Gender.MALE);
    e.setHireDate(DATE_FORMATTER.parse("2016-01-30"));
    e.setSalaries(null);
    em.persist(e);

    em.getTransaction().commit();

    TypedQuery<Employee> q = em.createQuery("select e from employee e where e.empNo = :empNo", Employee.class);
    q.setParameter("empNo", 99999);
    Employee inserted = q.getSingleResult();
    Assert.assertEquals(e, inserted);
}
 
Example 3
Project: aws-photosharing-example   File: ContentFacadeTest.java   Source Code and License Vote up 6 votes
@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 4
Project: Trabalhos-FIAP   File: UsuarioDao.java   Source Code and License Vote up 5 votes
public Usuario buscarUsuario(String apelido) {
	StringBuilder sb = new StringBuilder();
	sb.append("select u from Usuario u where apelido = '").append(apelido).append("'");
	
	TypedQuery<Usuario> query = super.em.createQuery(sb.toString(), Usuario.class);
	try {
		return query.getSingleResult();
	} catch (NoResultException e) {
		return null;
	}
}
 
Example 5
Project: testing_security_development_enterprise_systems   File: QuizService.java   Source Code and License Vote up 5 votes
public List<Quiz> getRandomQuizzes(int n, long categoryId){

        TypedQuery<Long> sizeQuery= em.createQuery(
                "select count(q) from Quiz q where q.subCategory.parent.id=?1", Long.class);
        sizeQuery.setParameter(1, categoryId);
        long size = sizeQuery.getSingleResult();

        if(n > size){
            throw new IllegalArgumentException("Cannot choose " + n + " unique quizzes out of the " + size + " existing");
        }

        Random random = new Random();

        List<Quiz> quizzes = new ArrayList<>();
        Set<Integer> chosen = new HashSet<>();

        while(chosen.size() < n) {

            int k = random.nextInt((int)size);
            if(chosen.contains(k)){
                continue;
            }
            chosen.add(k);

            TypedQuery<Quiz> query = em.createQuery(
                    "select q from Quiz q where q.subCategory.parent.id=?1", Quiz.class);
            query.setParameter(1, categoryId);
            query.setMaxResults(1);
            query.setFirstResult(k);

            quizzes.add(query.getSingleResult());
        }


        return  quizzes;
    }
 
Example 6
Project: cf-mta-deploy-service   File: DeployTargetDao.java   Source Code and License Vote up 5 votes
protected Dto findInternalByName(EntityManager manager, String name) throws NotFoundException {
    TypedQuery<Dto> query = createFindByNameQuery(name);
    try {
        return query.getSingleResult();
    } catch (NoResultException e) {
        throw new NotFoundException(Messages.DEPLOY_TARGET_WITH_NAME_NOT_FOUND, name);
    }
}
 
Example 7
Project: full-javaee-app   File: CandidatePersistence.java   Source Code and License Vote up 5 votes
public static Candidates login(String username, String password) {
    if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        String query;
        TypedQuery<Candidates> q;

        try {
            if (username.contains("@")) {
                query = "SELECT c FROM Candidates c WHERE c.email = :email";
                q = em.createQuery(query, Candidates.class);
                q.setParameter("email", username.toLowerCase().trim());
            } else {
                query = "SELECT c FROM Candidates c WHERE c.phone = :phone";
                q = em.createQuery(query, Candidates.class);
                q.setParameter("phone", CustomUtilities.cleanNumber(username));
            }
            Candidates candidate = q.getSingleResult();
            if (candidate != null && CustomUtilities.hashPassword(password, CustomUtilities.hexToBytes(candidate.getSalt()))[0].equals(candidate.getPassword())) {
                CandidateLoginLogs loginLog = addLoginLog(candidate);
                candidate.getLoginLog().add(loginLog);
                return candidate;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 8
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 5 votes
@Test
public void test118_FunctionToDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    TypedQuery<Date> q = em.createQuery("select to_date('2017-02-23', 'yyyy-MM-dd', :tz) from dual d", Date.class);
    q.setParameter("tz", TimeZone.getDefault().getID());
    Date result = q.getSingleResult();
    Assert.assertEquals("2017-02-23", sdf.format(result));
}
 
Example 9
Project: 112016.pizzeria-app   File: ClientService.java   Source Code and License Vote up 5 votes
/***Supprime un client de la base de donnee***/
public void deleteClient(Integer id){
	TypedQuery<Client> query = em.createQuery("SELECT c FROM Client c WHERE c.id = :id", Client.class);
	query.setParameter("id", id);
	Client c = query.getSingleResult();
	
	em.remove(c);
}
 
Example 10
Project: mid-tier   File: VirtualAccountArchivist.java   Source Code and License Vote up 5 votes
/**
 * Find account by its semantic key. Note this will throw {@link NoResultException} which will roll back the
 * transaction if the customer is not found.
 */
@LogDuration(limit = 50)
public VirtualAccount getAccount(Long vaNumber) {
    TypedQuery<VirtualAccount> q = em.createQuery("select va from VirtualAccount va where va.vaNumber=:number",
            VirtualAccount.class);
    q.setParameter("number", vaNumber);
    return q.getSingleResult();
}
 
Example 11
Project: mid-tier   File: CustomerArchivist.java   Source Code and License Vote up 5 votes
/**
 * Find customer by its semantic key. Note this will throw {@link NoResultException} which will roll back the
 * transaction if the customer is not found - if this is a problem consider using
 * {@link #findCustomer(String)}.
 */
@LogDuration(limit = 50)
public Customer getCustomer(String customerNo) {
    TypedQuery<Customer> q = em.createQuery("select c from Customer c where c.sid=:sid", Customer.class);
    q.setParameter("sid", customerNo);
    return q.getSingleResult();
}
 
Example 12
Project: mid-tier   File: VirtualAccountArchivist.java   Source Code and License Vote up 5 votes
/**
 * Find account by names. Note this will throw {@link NoResultException} which will roll back the
 * transaction if the account is not found.
 */
@LogDuration(limit = 50)
public VirtualAccount getAccountByAccountNumber(Long vaNumber) {
    TypedQuery<VirtualAccount> q = em.createQuery("select va from VirtualAccount va where va.vaNumber=:number",
            VirtualAccount.class);
    q.setParameter("number", vaNumber);
    return q.getSingleResult();
}
 
Example 13
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 4 votes
@Test
public void test117_FunctionToCharNumber() {
    TypedQuery<String> q = em.createQuery("select to_char(23.5678, '#0.0') from dual d", String.class);
    String result = q.getSingleResult();
    Assert.assertEquals("23.6", result.replace(",", "."));
}
 
Example 14
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 4 votes
@Test
public void test113_FunctionLength() {
    TypedQuery<Integer> q = em.createQuery("select length('abcdef') from dual d", Integer.class);
    Integer result = q.getSingleResult();
    Assert.assertEquals(Integer.valueOf("abcdef".length()), result);
}
 
Example 15
Project: coodoo-listing   File: ListingQuery.java   Source Code and License Vote up 4 votes
public Long count() {
    TypedQuery<Long> q = this.entityManager.createQuery(this.getQueryForCount());
    return q.getSingleResult();
}
 
Example 16
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 4 votes
@Test
public void test144_FunctionRound() {
    TypedQuery<Double> q = em.createQuery("select round(3.334) from dual d", Double.class);
    Double result = q.getSingleResult();
    Assert.assertEquals(Double.valueOf(Math.round(3.334d)), result);
}
 
Example 17
Project: 112016.pizzeria-app   File: PizzaService.java   Source Code and License Vote up 4 votes
public Pizza get(String code) {
	
	TypedQuery<Pizza> query = em.createQuery("SELECT p FROM Pizza p WHERE p.code =:code", Pizza.class);
	query.setParameter("code", code);
	return query.getSingleResult();
}
 
Example 18
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 4 votes
@Test
public void test115_FunctionRegexpReplace() {
    TypedQuery<String> q = em.createQuery("select regexp_replace('abc123ABC', '[0-9]+', '#') from dual d", String.class);
    String result = q.getSingleResult();
    Assert.assertEquals("abc#ABC", result);
}
 
Example 19
Project: WordnetLoom   File: LocalisedStringRepository.java   Source Code and License Vote up 4 votes
public LocalisedString findByKey(LocalisedKey key) {
    TypedQuery<LocalisedString> s = em.createQuery("SELECT s FROM  LocalisedString s WHERE s.key = :key", LocalisedString.class)
            .setParameter("key", key);
    return s.getSingleResult();
}
 
Example 20
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License Vote up 4 votes
@Test
public void test103_FunctionStdDevPop() {
    TypedQuery<Double> q = em.createQuery("select stddev_pop(s.salary) from salary s", Double.class);
    Double stddev = q.getSingleResult();
    Assert.assertTrue(Math.abs(stddev.doubleValue() - 16522.5459d) < 0.001d);
}