br.eti.danielcamargo.backend.hsnpts.core.business.AlunoService.java Source code

Java tutorial

Introduction

Here is the source code for br.eti.danielcamargo.backend.hsnpts.core.business.AlunoService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.eti.danielcamargo.backend.hsnpts.core.business;

import br.eti.danielcamargo.backend.common.core.persistence.Usuario;
import br.eti.danielcamargo.backend.common.exceptions.BusinessException;
import br.eti.danielcamargo.backend.common.exceptions.ValidationOccurrence;
import br.eti.danielcamargo.backend.hsnpts.core.persistence.Aluno;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Daniel
 */
@Service
public class AlunoService {

    @PersistenceContext
    EntityManager em;

    public Aluno getByUserId(Long userId) throws BusinessException {
        try {

            StringBuilder hql = new StringBuilder();

            hql.append("SELECT ");
            hql.append(" a ");
            hql.append("FROM ");
            hql.append("  Aluno a ");
            hql.append("  JOIN a.usuario u ");
            hql.append("WHERE ");
            hql.append("  u.id = :userId ");

            TypedQuery<Aluno> query = em.createQuery(hql.toString(), Aluno.class);
            query.setParameter("userId", userId);

            Aluno aluno = query.getSingleResult();

            return aluno;
        } catch (NoResultException e) {
            throw new BusinessException("hsnpts", new ValidationOccurrence("hsnpts.aluno-nao-encontrado"));
        }
    }

    @Transactional
    public Aluno create(Aluno aluno) {
        Usuario usuario = em.find(Usuario.class, aluno.getUsuario().getId());
        aluno.setUsuario(usuario);
        return em.merge(aluno);
    }

}