Problems to generate SQL command

Asked

Viewed 74 times

0

Hello, everyone. I am creating a project that handles user registration. In this project there will be several types of users. To simplify, let’s call the types 1,2 and 3. Depending on the type of user, are changed the screens and features that it can access.

To begin with, I have to explain about the table structure of my database. In my database I have a table called "user" where the user data is stored (name, Cpf, rg, etc...) and a table called "group" that stores the types of groups 1, 2, 3 and the description of the groups. And then, there is a table called "usuario_grupo" that associates the table "usuario" and "group".

The subject I am dealing with is the following: when a new user is registered, I am trying to insert in the table "usuario_grupo" a new record that associates the user id and the group id of this user. But I’m having a hard time building the sql code. When I run the code the error appears:

Unexpected token: values

I am sending the main files that deal with user registration.

User registration.java.

@Named
@ViewScoped
public class CadastroUsuarioBean implements Serializable {

private static final long serialVersionUID = 1L;

@Inject
private UsuariosRep usuariosRep;

@Inject
private EstadosRep estadosRep;

@Inject
private CidadeRep cidadeRep;

@Inject
private CadastroUsuarioService cadastroUsuarioService;

private Usuario usuario;

private Estado categoriaPai;

private Estado estado;

private Cidade cidade;

private String email;

private List<SelectItem> listEstados;

private List<SelectItem> listCidades;


public CadastroUsuarioBean() {
    limpar();
}

public boolean isEditando() {
    boolean resultado = false;
    if (this.usuario != null) {
        resultado = usuario.getId() != null;
    }
    return resultado;
}


public void inicializar() {
    listEstados = new ArrayList<SelectItem>();

    List<Estado> estados = estadosRep.raizes();

    for (Estado e : estados) {
        SelectItem item = new SelectItem();
        item.setLabel(e.getEstado_sigla());
        item.setValue(e);
        listEstados.add(item);
    }

    if(!isEditando())
    {
        usuario.setStatus("Ativo");
    }

    if (this.estado != null) {
        estados = estadosRep.raizes();
    }
}

public void limpar() {
    usuario = new Usuario();
    listEstados = new ArrayList<SelectItem>();
}

public void salvar() {
    if (usuariosRep.porCpf(this.usuario.getCpf()) != null){
        FacesUtil.addInfoMessage("Este CPF já existe!");
    }
    else{   
        usuariosRep.InserirTabelaUsuarioGrupo(this.usuario.getId());
        this.usuario = cadastroUsuarioService.salvar(this.usuario);
        limpar();
        FacesUtil.addInfoMessage("Cadastro de usuário efetuado com sucesso!");
    }
}

public void carregarCidades(){
    listCidades = new ArrayList<SelectItem>();
    List<Cidade> cidades = cidadeRep.cidadesDe(usuario.getEstado());
    for (Cidade c : cidades) {
        SelectItem item = new SelectItem();
        item.setLabel(c.getCidadeNome());
        item.setValue(c);
        listCidades.add(item);
    }
}

public Usuario getUsuario() {
    return usuario;
}

public void setUsuario(Usuario usuario) {
    this.usuario = usuario;
}

public Estado getEstado() {
    return estado;
}

public void setEstado(Estado estado) {
    this.estado = estado;
}

public List<SelectItem> getListEstados() {
    return listEstados;
}

public void setListEstados(List<SelectItem> listEstados) {
    this.listEstados = listEstados;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String register() {
    return "thanks?faces-redirect=true";
}

public Estado getCategoriaPai() {
    return categoriaPai;
}

public void setCategoriaPai(Estado categoriaPai) {
    this.categoriaPai = categoriaPai;
}

public Cidade getCidade() {
    return cidade;
}

public void setCidade(Cidade cidade) {
    this.cidade = cidade;
}

public List<SelectItem> getListCidades() {
    return listCidades;
}

public void setListCidades(List<SelectItem> listCidades) {
    this.listCidades = listCidades;
}

public UsuariosRep getUsuariosRep() {
    return usuariosRep;
}

public void setUsuariosRep(UsuariosRep usuariosRep) {
    this.usuariosRep = usuariosRep;
}   


}

Cadastrousuarioservice.java

public class CadastroUsuarioService implements Serializable {

private static final long serialVersionUID = 1L;
@Inject
private UsuariosRep usuarios;

public Usuario salvar(Usuario usuario) {
    return usuarios.guardar(usuario);
}

@Transactional
public void excluir(Usuario usuario) throws NegocioException {
    usuario = this.usuarios.porNome(usuario.getNome());
    this.usuarios.remover(usuario);
}
}

Usuariosrep.java

public class UsuariosRep implements Serializable {

private static final long serialVersionUID = 1L;
@Inject
private EntityManager manager;

public Usuario guardar(Usuario usuario) {

    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    usuario = manager.merge(usuario);
    trx.commit();
    return usuario;
}

public Usuario porCpf(String cpf){
    Usuario usuario = null;

    try{
        usuario = this.manager.createQuery("from Usuario where cpf = :cpf", Usuario.class)
                .setParameter("cpf", cpf).getSingleResult();
    }catch (NoResultException e){
        // Nenhum usuario encontrado com o nome informado.
    }
    return usuario;
}

public Usuario porNome(String nome) {
    Usuario usuario = null;

    try{
    usuario = this.manager.createQuery("from Usuario where lower(nome) = :nome", Usuario.class)
            .setParameter("nome", nome.toLowerCase()).getSingleResult();
    }catch (NoResultException e){
        // Nenhum usuario encontrado com o nome informado.
    }
    return usuario;
}

public void InserirTabelaUsuarioGrupo(Long id){
    Usuario usuario = null;
    usuario = (Usuario) this.manager.createQuery("Insert into usuario_grupo(usuario_id,grupo_id) values(id,1)");
}

public Usuario porId(Long id)
{
    return manager.find(Usuario.class, id);
}

public List<Usuario> listaDeUsu() 
{
    return manager.createQuery("from Usuario", Usuario.class).getResultList();
}

public List<Usuario> raizes()
{
    return  manager.createQuery("from Usuario",Usuario.class).getResultList(); 
}

@SuppressWarnings("unchecked")
public List<Usuario> filtrados(UsuarioFilter filtro) {

    Session session = manager.unwrap(Session.class);

    Criteria criteria = session.createCriteria(Usuario.class);

    if (filtro.getNome() != "") 
    {
        System.out.println(filtro.getNome());
        criteria.add(Restrictions.eq("nome", filtro.getNome()));
    }

    if (filtro.getStatus() != null)
    {
        criteria.add(Restrictions.eq("status", filtro.getStatus()));
    }

    // orderBy do SQL
    return criteria.addOrder(Order.asc("id")).list();
}

public void remover(Usuario usuario) {
    this.manager.remove(usuario);
    EntityTransaction trx = manager.getTransaction();
    trx.begin();
    manager.flush();
    trx.commit();
}

public Usuario porEmail(String email) {
    Usuario usuario = null;

    try{
        usuario = this.manager.createQuery("from Usuario where lower(email) = :email", Usuario.class)
                .setParameter("email", email.toLowerCase()).getSingleResult();
    }
    catch (NoResultException e){
        FacesUtil.addErrorMessage("Nenhum usuário encontrado");
    }
    return usuario;
}
}

Among the codes, in Usuariosrep.java you will find a method called Inserirtabelausuarupo. This is the method I am using to insert a new record in the "user group" table. And in Cadastrousuariobean.java, in the method "save" is being called the method Inserirtabelausuarupo.

In Insertabelausuarupo you will see that I am inserting 1 as the group id. I am inserting 1 only for test purposes. After solving this error, I intend to insert dynamically.

I appreciate any advice or opinion.

  • You want what at last?

2 answers

1

It seems to me that you are confusing the language of JPA/Hibernate (JPQL or HQL) with real SQL.

I checked in here https://docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/ch11.html#d5e2800 and HQL has the INSERT command but it doesn’t use the VALUES word, whereas JPQL doesn’t even have INSERT, it only has the.persist() call in Java (I didn’t even know it, I knew only the INSERT of normal SQL and I thought it was the same in JPQL).

Also, remember that JPQL/HQL works with class names and attributes as declared in Java, which may be different from table and column names (It is possible that there is not even a user entity_groupfrom the point of view of JPQL/HQL, depending on how you did the object-relational mapping).

I would suggest replacing createQuery with a createNativeQuery in your INSERT that actually uses SQL. And don’t forget a . executeUpdate() at the end. The executaeUpdate is used for both updates and Inserts. It should work, or at least change the error message to put you in the right direction :-)

0

Look, if you want to insert the user into your relationship with the group just explore JPA and Hibernate, you don’t need to use SQL. You’d do it this way:

1 - Add user and group mapping to the created entity. CASCADE ALL was used so that the insertion/update/deletion of the user’s record affects the relationship record in Usuariogroup.

Class Usuario {
     //Todos os atributos do usuário
     //Relacionamento entre usuário e grupo
     //
     @OneToMany(mappedBy = "usuario", cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
     private List<UsuarioGrupo> usuarioGrupo;
}

2 - In the record persistence, just call the JPA persist:

//JPA
public void inserirUsuario(Usuario usuario) {
   manager.getTransaction().begin();
   manager.persist(usuario);
   manager.getTransaction().commit();
}

When the persist is called, both the user record and your relationship will be created in the User table as long as you have filled in the User entity with this information before calling the User method. This will happen because you used CASCADE to facilitate the work! Using JPA you will not need to use SQL anywhere, and it is not recommended because the abstraction of JPQL allows you to change banks without changing ANYTHING in the business code! I hope I’ve helped ^^

NOTE: Keep the name of the methods with the first letter in low box, following the Java nomenclature patterns (http://www.oracle.com/technetwork/java/codeconventions-135099.html).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.