Error using Hibernate to generate tables and doubts about

Asked

Viewed 255 times

0

I am creating a webservice using Maven to manage the dependencies of my project. At the moment, I’m looking to create a database based on my models.

I have four doubts and a problem in my attempt:
1) How Java Creates Foreign Key ?
2) How do I make Java to create the database ?
3) Is it possible to create only one . SQL ? 4)

This is my problem:

javax.servlet.Servletexception: A Multiexception has 2 exceptions. They are: 1. javax.persistence.Persistenceexception: No Persistence Provider for Entitymanager named persistence_unit_together 2. java.lang.Illegalstateexception: Unable to perform Operation: create on br.com.felipejunges.juntos.controller.Personal

org.glassfish.jersey.servlet.Webcomponent.serviceImpl(Webcomponent.java:487) org.glassfish.jersey.servlet.Webcomponent.service(Webcomponent.java:425) org.glassfish.jersey.servlet.Servletcontainer.service(Servletcontainer.java:383) org.glassfish.jersey.servlet.Servletcontainer.service(Servletcontainer.java:336) org.glassfish.jersey.servlet.Servletcontainer.service(Servletcontainer.java:223) org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:53)

Some data from my project:

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
                                http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" 
             version="2.0" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns="http://java.sun.com/xml/ns/persistence">

   <persistence-unit name="persistence_unit_juntos" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
         <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/juntosHibernate"/>
         <property name="javax.persistence.jdbc.user" value="root"/>
         <property name="javax.persistence.jdbc.password" value="root"/>
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.hbm2ddl.auto" value="create"/>
      </properties>
   </persistence-unit>
</persistence>

method I’m calling in controller:

@GET
    @Produces("application/json; charset=UTF-8")
    @Path("/lista")
    public List<Pessoa> ListarTudo(){

        List<Pessoa> pessoas =  new ArrayList<Pessoa>();

        List<Pessoa> listaEntityPessoas = repository.ListarTudo();

        for (Pessoa entity : listaEntityPessoas) {

            pessoas.add(new Pessoa(entity.getId(), entity.getNome(), entity.getSobrenome(), entity.getEmail(), 
                    entity.getSenha(), entity.getTelefone(), entity.getCep(), entity.getLogin(), 
                    entity.getRegistro(), entity.getGacesso_id(), entity.isBanAtivo(), 
                    entity.getLocalizacaoAtual()));
        }

        return pessoas;
    }

Class Pessoarepository:

public class PessoaRepository {

    private final EntityManagerFactory entityManagerFactory;

    private final EntityManager entityManager;

    public PessoaRepository(){

        /*CRIANDO O NOSSO EntityManagerFactory COM AS PORPRIEDADOS DO ARQUIVO persistence.xml */
        this.entityManagerFactory = Persistence.createEntityManagerFactory("persistence_unit_juntos");

        this.entityManager = this.entityManagerFactory.createEntityManager();
    }

    /**
     * CRIA UM NOVO REGISTRO NO BANCO DE DADOS
     * */
    public void Salvar(Pessoa pessoaEntity){

        this.entityManager.getTransaction().begin();
        this.entityManager.persist(pessoaEntity);
        this.entityManager.getTransaction().commit();
    }

    /**
     * ALTERA UM REGISTRO CADASTRADO
     * */
    public void Alterar(Pessoa pessoaEntity){

        this.entityManager.getTransaction().begin();
        this.entityManager.merge(pessoaEntity);
        this.entityManager.getTransaction().commit();
    }

    /**
     * RETORNA TODAS AS PESSOAS CADASTRADAS NO BANCO DE DADOS 
     * */
    @SuppressWarnings("unchecked")
    public List<Pessoa> ListarTudo(){

        return this.entityManager.createQuery("SELECT p FROM Pessoa p ORDER BY p.nome").getResultList();
    }

    /**
     * CONSULTA UMA PESSOA CADASTRA PELO CÓDIGO
     * */
    public Pessoa GetPessoa(Integer id){

        return this.entityManager.find(Pessoa.class, id);
    }

    /**
     * EXCLUINDO UM REGISTRO PELO CÓDIGO
    **/
    public void Excluir(Integer id){

        Pessoa pessoa = this.GetPessoa(id);

        this.entityManager.getTransaction().begin();
        this.entityManager.remove(pessoa);
        this.entityManager.getTransaction().commit();

    }

    public Pessoa Login(String email){

        return (Pessoa) this.entityManager
                .createQuery("SELECT p FROM Pessoa p WHERE p.email  = :pemail")
                .setParameter("pemail", email).getSingleResult();
    }

    public boolean HabilitarConta(Pessoa pessoa){
        return false;
    }

}

And this is my Model/Entity:

@Entity
@Table(name="pessoa")
public class Pessoa {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="nome")
    private String nome;

    @Column(name="sobrenome")
    private String sobrenome;

    @Column(name="email")
    private String email;

    @Column(name="senha")
    private String senha;

    @Column(name="telefone")
    private String telefone;

    @Column(name="cep")
    private Cep cep;

    @Column(name="login")
    private Timestamp login;

    @Column(name="registro")
    private Timestamp registro;

    @Column(name="gacesso_id")
    private Permissao gacesso_id;

    @Column(name="banAtivo")
    private boolean banAtivo;

    @Column(name="localizacaoAtual")
    private Localizacao localizacaoAtual;

    public Pessoa() {

    }

    public Pessoa(int id, String nome, String sobrenome, String email, String senha, 
            String telefone, Cep cep, Timestamp login, Timestamp registro, 
            Permissao gacesso_id, boolean banAtivo, Localizacao localizacaoAtual) {

        super();
        this.id = id;
        this.nome = nome;
        this.sobrenome = sobrenome;
        this.email = email;
        this.senha = senha;
        this.telefone = telefone;
        this.cep = cep;
        this.login = login;
        this.registro = registro;
        this.gacesso_id = gacesso_id;
        this.banAtivo = banAtivo;
        this.localizacaoAtual = localizacaoAtual;


    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getSobrenome() {
        return sobrenome;
    }
    public void setSobrenome(String sobrenome) {
        this.sobrenome = sobrenome;
    }
    public String getSenha() {
        return senha;
    }
    public void setSenha(String senha) {
        this.senha = senha;
    }
    public String getTelefone() {
        return telefone;
    }
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }
    public Cep getCep() {
        return cep;
    }
    public void setCep(Cep cep) {
        this.cep = cep;
    }
    public Timestamp getLogin() {
        return login;
    }
    public void setLogin(Timestamp login) {
        this.login = login;
    }
    public Timestamp getRegistro() {
        return registro;
    }
    public void setRegistro(Timestamp registro) {
        this.registro = registro;
    }
    public Permissao getGacesso_id() {
        return gacesso_id;
    }
    public void setGacesso_id(Permissao gacesso_id) {
        this.gacesso_id = gacesso_id;
    }

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

    public Localizacao getLocalizacaoAtual() {
        return localizacaoAtual;
    }

    public void setLocalizacaoAtual(Localizacao localizacaoAtual) {
        this.localizacaoAtual = localizacaoAtual;
    }

    public boolean isBanAtivo() {
        return banAtivo;
    }

    public void setBanAtivo(boolean banAtivo) {
        this.banAtivo = banAtivo;
    }
}

I tested with /register (Save to Repository) and it didn’t work.
In case, I have another Webservice project that I followed a tutorial and adapted to my solution for presentation in class, now I want to create for my TCC.
I didn’t have it on the other project:
a) Automatic database creation, i.e., I created . sql at hand;
b) References of other models in a template.

Edited:

HTTP Status 500 – Internal Server Error

Type Exception Report

Message A MultiException has 2 exceptions. They are:

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: A MultiException has 2 exceptions.  They are:
1. javax.persistence.PersistenceException: [PersistenceUnit: persistence_unit_juntos] Unable to build Hibernate SessionFactory
2. java.lang.IllegalStateException: Unable to perform operation: create on br.com.felipejunges.juntos.controller.PessoaController

    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:487)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

A MultiException has 2 exceptions.  They are:
1. javax.persistence.PersistenceException: [PersistenceUnit: persistence_unit_juntos] Unable to build Hibernate SessionFactory
2. java.lang.IllegalStateException: Unable to perform operation: create on br.com.felipejunges.juntos.controller.PessoaController

    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:391)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:767)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:706)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

javax.persistence.PersistenceException: [PersistenceUnit: persistence_unit_juntos] Unable to build Hibernate SessionFactory
    org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:884)
    org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    br.com.felipejunges.juntos.repository.PessoaRepository.<init>(PessoaRepository.java:20)
    br.com.felipejunges.juntos.controller.PessoaController.<init>(PessoaController.java:21)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1350)
    org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:271)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:365)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:767)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:706)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.hibernate.MappingException: Could not determine type for: br.com.felipejunges.juntos.entity.Pessoa, at table: ban, for columns: [org.hibernate.mapping.Column(admin_id)]
    org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:411)
    org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:384)
    org.hibernate.mapping.Property.isValid(Property.java:226)
    org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:529)
    org.hibernate.mapping.RootClass.validate(RootClass.java:265)
    org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
    org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:464)
    org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:881)
    org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
    javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    br.com.felipejunges.juntos.repository.PessoaRepository.<init>(PessoaRepository.java:20)
    br.com.felipejunges.juntos.controller.PessoaController.<init>(PessoaController.java:21)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    java.lang.reflect.Constructor.newInstance(Unknown Source)
    org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1350)
    org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:271)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:365)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:471)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:162)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2072)
    org.jvnet.hk2.internal.ServiceLocatorImpl.internalGetService(ServiceLocatorImpl.java:767)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:706)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:172)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:284)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:109)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:92)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:61)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:318)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

1 answer

0


The first error (No Persistence Provider for Entitymanager) is usually because Hibernate did not find the persistence.xml file. He usually stays in /src/META-INF.

Regarding the automatic creation of your database, the property "Hibernate.hbm2ddl.auto", which is already in your persistence.xml, is responsible for this. The possible values are:

  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying Previous data.
  • create-drop: drop the schema when the Sessionfactory is closed explicitly, typically when the application is stopped.

Finally, about creating FK: it is automatically created by Hibernate, according to relationship Annotations (@Manytomany, @Manytoone, @Onetomany).

I suggest starting by solving the first problem, which is to make Hibernate find your persistence.xml file..

  • I fixed the localization error and some dependencies, and now was introducing me: [Persistenceunit: persistence_unit_together] Unable to build Hibernate Sessionfactory, this would have to do with COLUMN referencing to other objects ?

  • Could you post the full stack trace of the exception? This seems to be a more general error and usually the root cause is shown at the end of the stack trace.

  • I put the log of the new error to post

  • The root cause is "org.hibernate.Mappingexception: Could not determine type for: br.com.felipejunges.juntos.Entity.Pessoa, at table: ban, for Columns: [org.hibernate.Mapping.Column(admin_id)]". Hibernate couldn’t identify the type for a column called "admin_id". I couldn’t find it in his original post. Could send?

  • So I think I know the error, are the Foreign key, that I did not mention in the models correctly at the time! I will be leaving the completed answer, because the initial doubt, you already answered! Thank you!

Browser other questions tagged

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