Error entering data into JPA

0
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
// pode usar para alterar o nome da tabela la no banco
//@Table(name = "")
public class Usuario {

    @Id
    @GeneratedValue
    private Long id;
    @Column(name= "login_usu")
    private String login;
    private String senha;

    public void mostrar() {
        System.out.printf("Id: %-5d Login: %-30s Senha: %-20s \n", id, login, senha);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

}
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ConnectionFactory {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("aula09");
    public static EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

}
import javax.persistence.EntityManager;

public class Principal {

    public static void main(String[] args) {

        Usuario u = new Usuario();
        u.setLogin("[email protected]");
        u.setSenha("senha123");

        EntityManager em = ConnectionFactory.getEntityManager();
        em.getTransaction().begin();
        em.persist(u);
        em.getTransaction();
        em.close();

    }
}

When you run, everything is created but the information is not entered in the database.

    
asked by anonymous 11.02.2017 / 14:39

1 answer

2

Assuming your settings in persistence.xml are correct, do the following:

  • "Write down" your senha attribute with @Column(name="NOME_DA_COLUNA")
  • In the line next to the persist(u) method, call the commit() method with: em.getTransaction().commit();
  • At the end it will look like this (in a nutshell):

    @Entity
    public class Usuario {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @Column(name= "login_usu")
        private String login;
    
        @Column(name="NOME_DA_COLUNA")
        private String senha;
    
        //getters e setters
    
    }
    
    public class Principal {
    
        public static void main(String[] args) {
    
            Usuario u = new Usuario();
            u.setLogin("[email protected]");
            u.setSenha("senha123");
    
            EntityManager em = ConnectionFactory.getEntityManager();
            em.getTransaction().begin();
            em.persist(u);
            em.getTransaction().commit();
            em.close();
        }
    }
    
        
    11.02.2017 / 15:33