Estou criando um webservice utilizando o Maven para gerenciar as dependências do meu projeto. No momento, estou querendo criar um banco de dados com base nos meus modelos.
Tenho quatro duvidas e um problema na minha tentativa:
1) Como faço para com o Java criar Foreign Key ?
2) Como faço para o Java criar o banco de dados ?
3) É possível criar apenas um arquivo .SQL ?
4)
O meu problema é este:
javax.servlet.ServletException: A MultiException has 2 exceptions. They are: 1. javax.persistence.PersistenceException: No Persistence provider for EntityManager named persistence_unit_juntos 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)
Alguns dados do meu projeto:
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>
método que estou chamando no 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;
}
Classe 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;
}
}
E este é o meu Modelo/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;
}
}
Testei com o /cadastrar (Salvar no Repositório) e não funcionou.
No caso, tenho outro projeto de Webservice que segui um tutorial e adaptei para minha solução para apresentação na aula, agora estou querendo criar para meu TCC.
O não tinha no outro projeto:
a) Criação automática do banco, ou seja, criei o .sql na mão;
b) Referências de outros modelos em um modelo.
Editado:
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.