JPA+ Hibernate+ Maven + NetBeans = HTTP Status 500 - java

I have been trying to figure it out for a few days but today I gave up. I got the HTTP Status Error when I try to create Entity Manager Factory.
Full Stack Trace:
Type Exception Report
Message Error processing webservice request
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Error processing webservice request
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
<openjpa-3.0.0-r422266:1833209 fatal user error> org.apache.openjpa.persistence.ArgumentException: The persistence provider is attempting to use properties in the persistence.xml file to resolve the data source. A Java Database Connectivity (JDBC) driver or data source class name must be specified in the openjpa.ConnectionDriverName or javax.persistence.jdbc.driver property. The following properties are available in the configuration: "org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#393fa2d".
org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:71)
org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:850)
org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:603)
org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1520)
org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:533)
org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:458)
org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:122)
org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:1035)
org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:1026)
org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:643)
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203)
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:154)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:246)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:162)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:152)
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:58)
dao.Dao.getUser(Dao.java:15)
tk.spartan.controller.GetUser.list(GetUser.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:193)
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:103)
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:253)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
So it's a little weird that I get openjpa error when in persistance.xml I've got :
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="baza" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>beans.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="javax.persistence.jdbc.user" value="bd2a4c789dfa24" />
<property name="javax.persistence.jdbc.password" value="xxxx" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://eu-cdbr-west-02.cleardb.net/heroku_48a75ca44077046?reconnect=true" />
<!-- <property name="hibernate.hbm2ddl.auto" value="update"/> -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.cache.use_second_level_cache" value="false"/>
<property name="hibernate.archive.autodetection" value="true"/>
</properties>
</persistence-unit>
</persistence>
and my Entity class looks like:
package beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User {
#Column(name = "iduser")
#Id
private Integer iduser;
#Column(name = "user")
private String user;
#Column(name = "password")
private String password;
#Column(name = "role")
private String role;
public User() {
}
public User(int iduser, String user, String pass, String role) {
this.iduser = iduser;
this.user = user;
this.password = password;
this.role = role;
}
public User(Integer iduser) {
this.iduser = iduser;
}
public Integer getIduser() {
return iduser;
}
public void setIduser(Integer iduser) {
this.iduser = iduser;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
So I'm a little bit confused right now. I've been searching for that kind of error but i didn't find a solution for that.
What it could be?
Added:
#Path("user")
public class GetUser
{
#GET
#Produces(MediaType.TEXT_PLAIN)
public List<User> list ()
{
Dao dao = new Dao();
User user = new User();
List<User> userListed = dao.getUser(user);
return userListed;
}
and structure:

I think you should include mysql driver to your jar dependency(pom.xml).
The error message said: The driver is unknown.

Related

Why hibernate doesn't create tables automatically even with hibernate.hbm2ddl.auto" value="create"?

I'm trying to force hibernate to create a student table if it doesn't exist, but without success, Hibernate library should be able to do that, but I'm getting an error saying there is no such table in the database, not sure what is the problem :
Details:
Student class
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Student {
#Id
int id;
int phoneNumber;
public Student() {
}
public Student(int id, int phoneNumber) {
this.id = id;
this.phoneNumber = phoneNumber;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Main class
public class Main {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ss");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Student student = new Student(5,55);
entityManager.getTransaction().begin();
entityManager.persist(student);
entityManager.getTransaction().commit();
}
}
Persistance.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ss" transaction-type="RESOURCE_LOCAL">
<class>com.youssef.Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sotamag" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
</properties>
</persistence-unit>
</persistence>
Note:
-I've added the following property <property name="hibernate.hbm2ddl.auto" value="create"/> to force hibernate to create the table, but still, I get the error saying there is no such table in the database.
-i'm using MySQL as database
`
If you are using MySQL5 or above, you can try changing your Dialect to:
<property name="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</property>

Hibernate JAVA | How to get an instance of EntityManager WITHOUT creating a new table?

every time that I want to get the instance of Entity Manager is creating new tables in the database, so how I can get the EntityManager (to insert, delete, update the database) in Postgresql without creating new tables?
Entity "Medico":
#Entity
#Table(name = "medico")
#SequenceGenerator (name = "medico_seq",sequenceName="medico_seq",allocationSize = 1, initialValue = 1)
public class Medico implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "medico_seq")
private Integer id = null;
private String especializacao;
private Integer diasRetorno;
private Time tempoConsulta;
private String nome;
private String cpf;
private String email;
private String senha;
private String telefone;
private String cidade;
private String estado;
private String cep;
private String endereco;
private String bairro;
private Integer enderecoNumero;
public Medico(String especializacao, Integer diasRetorno, Time tempoConsulta, String nome, String cpf, String email, String senha, String telefone, String cidade, String estado, String cep, String endereco, String bairro, Integer enderecoNumero) {
//...
}
//getters and setters
}
"MedicoDAO"
package dao;
import entidade.Medico;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.hibernate.Session;
public class MedicoDAO {
public Medico salvar (Medico medico){
EntityManager em = Persistence.createEntityManagerFactory("PersistenciaPU").createEntityManager();
try{em.getTransaction().begin();
if(medico.getId()==null){
em.persist(medico); //Faz o insert
}
else{
medico = em.merge(medico); // Faz o update
}
em.getTransaction().commit();
}catch(Exception ex){
System.err.println("ERRO123: "+ex.getMessage());
}finally{
em.close();
}
em.close();
return medico;
}
}
"Persistence.xml"
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PersistenciaPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entidade.HorarioAtendimentoMedico</class>
<class>entidade.Medico</class>
<class>entidade.Paciente</class>
<properties>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/clinica"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.password" value="123456"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
main:
package persistencia;
import dao.Auxiliar;
import dao.MedicoDAO;
import entidade.Medico;
import java.sql.Time;
import javax.persistence.Persistence;
public class Persistencia {
public static void main(String[] args) {
Time t = new Time(2,3,4);
Medico medico = new Medico("Cirurgiao",7,t,"Roberto","555.458.912-12","roberto#medico.com","12345","48 3275 0463", "Florianópolis", "SC", "88.222-200","Rua Bonita","Lagoa",12);
MedicoDAO dao = new MedicoDAO();
dao.salvar(medico);
}
}
Error:
Exception in thread "main" javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [create table medico]
Caused by: org.postgresql.util.PSQLException: ERROR: relation "medico" already exists
I can't see the Image. but try to change
<property name="hibernate.hbm2ddl.auto">create</property> // create new schema
to this:
<property name="hibernate.hbm2ddl.auto">update</property> // update the schema
I got!
What was needed is delete this line of the persistence.xml:
property name="javax.persistence.schema-generation.database.action" value="create"/
Thanks for help me to notice this line

DAO methods all return NullPointerException

I'm developing a little web app for an exam purpose, but I'm encountering several problems with the Dao methods, they all return a NullPointerException.
This is the Façade:
#Stateless(name = "administratorFacade")
public class AdministratorFacade {
#PersistenceContext(unitName = "clinic-unit")
private EntityManager em;
public Administrator getAdministrator(String username){
AdministratorDaoJPA administratorDao = new AdministratorDaoJPA();
Administrator administrator = administratorDao.findByUsername(username);
return administrator;
} //An example of method that uses DAO
This is the DAO:
public class AdministratorDaoJPA implements AdministratorDao {
#PersistenceContext(unitName = "clinic-unit", type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Override
public Administrator findByUsername(String username){
Query query = em.createQuery("SELECT a FROM Administrator a WHERE a.username=?");
return (Administrator)query.setParameter(1,username).getSingleResult();
}
And there is Administrator.java:
#Entity
#NamedQuery(name="allAdministrators", query="SELECT a FROM Administrator a")
public class Administrator {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(unique = true, nullable = false)
private String username;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private String surname;
#Column(nullable = false)
private String pwd;
public Administrator(){}
public Administrator(String username, String name, String surname, String pwd) {
this.username=username;
this.name = name;
this.surname=surname;
this.pwd = pwd;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username ;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSurname() {
return surname;
}
public void setSurname(String surName) {
this.surname = surName;
}
#Override
public boolean equals(Object o) {
Administrator adm = (Administrator) o;
return adm.getUsername().equals(this.getUsername());
}
#Override
public int hashCode() {
return this.getUsername().hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Adinistrator");
sb.append("{id='").append(id);
sb.append(", name='").append(name);
sb.append(", surname='").append(surname);
sb.append(", username='").append(username);
sb.append("}\n");
return sb.toString();
}
}
And finally the persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="clinic-unit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>PostgreSQL Database</jta-data-source>
<class>it.clinic.model.Indicator</class>
<class>it.clinic.model.Administrator</class>
<class>it.clinic.model.Exam</class>
<class>it.clinic.model.ExamTypology</class>
<class>it.clinic.model.Medic</class>
<class>it.clinic.model.Patient</class>
<class>it.clinic.model.Prerequisite</class>
<properties>
<!-- ad ogni esecuzione viene creato lo schema, cancellando il contenuto delle tabelle
<property name="hibernate.hbm2ddl.auto" value="create"/> -->
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!--- Per avere info sulle istruzioni SQL inviate al db -->
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.archive.autodetection" value="class"/>
</properties>
</persistence-unit>
</persistence>
Stacktrace:
java.lang.NullPointerException
it.clinic.persistence.ExamTypologyDaoJPA.findAll(ExamTypologyDaoJPA.java:54)
it.clinic.facade.AdministratorFacade.getAllExamTypologies(AdministratorFacade.java:53)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:236)
org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:203)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:265)
org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:260)
org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:89)
org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:347)
it.clinic.facade.AdministratorFacade$$LocalBeanProxy.getAllExamTypologies(it/clinic/facade/AdministratorFacade.java)
it.clinic.controller.ExamTypologyController.examTypologiesList(ExamTypologyController.java:35)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.apache.tomee.catalina.JavaeeInstanceManager.postConstruct(JavaeeInstanceManager.java:163)
org.apache.tomee.mojarra.TomEEInjectionProvider.invokePostConstruct(TomEEInjectionProvider.java:57)
com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:221)
com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:103)
com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:257)
com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:117)
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
com.sun.faces.el.ChainTypeCompositeELResolver.getValue(ChainTypeCompositeELResolver.java:90)
org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:96)
org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:80)
org.apache.el.parser.AstValue.getValue(AstValue.java:137)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:115)
org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:151)
javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
org.apache.jsp.ExamTypologies_jsp._jspx_meth_c_005fforEach_005f0(ExamTypologies_jsp.java:280)
org.apache.jsp.ExamTypologies_jsp._jspService(ExamTypologies_jsp.java:232)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:642)
com.sun.faces.application.view.JspViewHandlingStrategy.executePageToBuildView(JspViewHandlingStrategy.java:363)
com.sun.faces.application.view.JspViewHandlingStrategy.buildView(JspViewHandlingStrategy.java:153)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.apache.openejb.server.httpd.WebBeansFilter.doFilter(WebBeansFilter.java:52)
I'm using JPA with Tomee and JSF 2.2.
I hope you will help me to go through this :)
You're using
new AdministratorDaoJPA()
to get your DAO. So the container can't inject anything into that object, and the entityManager field thus has its default value: null.
For injection to happen, you must let the container create and inject the objects.
You also don't need the entity manager in your facade, so there is no point in injecting it there. What you need to inject is the DAO:
#Inject
private AdministratorDaoJPA administratorDao;

Spring error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL

I learn spring and I have a problem:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/PanTau_acc/Desktop/SPRING/target/classes/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: com.donutek] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:800)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:444)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:791)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:294)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1349)
at org.eclipse.jetty.maven.plugin.JettyWebAppContext.startWebapp(JettyWebAppContext.java:296)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1342)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:741)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:505)
at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:365)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:163)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:132)
at org.eclipse.jetty.server.Server.start(Server.java:387)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:114)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
at org.eclipse.jetty.server.Server.doStart(Server.java:354)
at org.eclipse.jetty.maven.plugin.JettyServer.doStart(JettyServer.java:73)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:534)
at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:357)
at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:167)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMav
en.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: com.donutek] Unable to build Hibernate SessionFactory
When I run the project with my entity LoginLog.
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "login_log")
public class LoginLog extends BaseObject implements Serializable {
private Date date;
private String ip;
private User user;
public LoginLog() {
//
}
public LoginLog(Date date, String ip, User user) {
this.date = date;
this.ip = ip;
this.user = user;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Base object is:
#MappedSuperclass
public class BaseObject {
private Long id;
/**
*
* #return true if the entity hasn't been persisted yet
*/
#Transient
public boolean isNew() {
return id == null;
}
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
applicationContext.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
>
<context:annotation-config/>
<context:component-scan base-package="com.donutek.**.*"/>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" destroy-method="destroy">
<property name="persistenceXmlLocation" value="classpath:/META-INF/persistence.xml"/>
<property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/>
<property name="packagesToScan" value="com.donutek.**.domain"/>
<property name="persistenceUnitName" value="com.donutek"/>
</bean>
<bean id="hibernateVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- Transaction manager for a single EntityManagerFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
</beans>
I think, that problem is in public LoginLog(Date date, String ip, User user), because when i run the code without User user in LoginLog class, it's normaly working.
Can you help me?
Thank you for your advice.
Spring version is: 4.2.4.RELEASE
EDIT:
user.java is:
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User extends BaseObject {
/**
* Login, unique
*/
private String email;
/**
* Secret for signing-in
*/
private String password;
/**
* Date of user registration
*/
private Date dateRegistration;
/**
* User nick name
*/
private String nickName;
/**
* State of user accoutn
*/
private UserState userAccState;
public User() {
//
}
public User(String email, String password, String nickName) {
this.email = email;
this.password = password;
this.dateRegistration = new Date();
this.nickName = nickName;
this.userAccState = UserState.acc_waitingForActivated;
}
#Column(unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDateRegistration() {
return dateRegistration;
}
public void setDateRegistration(Date dateRegistration) {
this.dateRegistration = dateRegistration;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public UserState getUserAccState() {
return userAccState;
}
public void setUserAccState(UserState userAccState) {
this.userAccState = userAccState;
}
}
persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="com.donutek" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.validator.apply_to_ddl" value="true" />
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="300"/>
</properties>
</persistence-unit>
</persistence>
EDIT 2:
full stacktrace:
(a can't add stacktrace, because is to long).
Link:
http://pastebin.com/LkgwqtJZ
Provide hibernate mapping for the User object in LoginLog class:
Example:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "email", nullable = false)
public User getUser() {
return user;
}

org.hibernate.exception.JDBCConnectionException: Could not open connection, hibernate, h2

I am making a sample application using hibernate and h2 database. I have an entity class (actually more than 1, but let's start with making it work for 1 of them), which looks like that:
package ~path.examples.testjpa.domain;
import javax.persistence.*;
import java.util.*;
/**
* Created by Me on 2015-04-20.
*/
#Entity
#Table(name= "Persons")
public class Person {
#Id
#Column(nullable= false)
#GeneratedValue(strategy = GenerationType.AUTO)
protected int persId;
#Column(nullable= false, length = 50)
private String firstName;
#Column(nullable= false, length = 50)
private String surname;
#Column(nullable= true, length = 50)
private String emailAddress;
#OneToOne
private Account account;
#OneToMany(targetEntity = PhoneNumber.class)
List phoneNumberList;
public Person() {
// empty
}
public Person(int persId, String firstName, String surname, String emailAddress) {
this.persId = persId;
this.firstName = firstName;
this.surname = surname;
this.emailAddress = emailAddress;
}
public List getPhoneNumberList() {
return phoneNumberList;
}
public void setPhoneNumberList(List<PhoneNumber> phoneNumberList) {
this.phoneNumberList= phoneNumberList;
}
public int getPersId() {
return persId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#Override
public String toString() {
return "Person [persId=" + persId + ", firstName=" + firstName + ", surname=" + surname + ", emailAddress=" + emailAddress + "]";
}
}
Here is my persistance.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="jpaTest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:~/test" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.password" value="" />
<property name="schemaUpdate" value="true" />
</properties>
</persistence-unit>
</persistence>
and the jpaTest class, supposed to make the connection
package ~path.examples.service;
import ~path.examples.testjpa.domain.Person;
import javax.persistence.*;
/**
* Created by Me on 2015-04-22.
*/
public class JpaTest {
public static void main(String args[]) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jpaTest");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
Person person = new Person();
person.setFirstName("Charles");
person.setSurname("Dickens");
em.persist(person);
userTransaction.commit();
em.close();
entityManagerFactory.close();
}
}
When I try to run it, I get the following:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289)
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1371)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:60)
at eu.rivetgroup.examples.service.JpaTest.main(JpaTest.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: org.hibernate.exception.JDBCConnectionException: Could not open connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1263)
at org.hibernate.ejb.TransactionImpl.begin(TransactionImpl.java:57)
... 6 more
Caused by: java.sql.SQLException: No suitable driver found for jdbc:h2:~/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:276)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 11 more
My guess is, that I'm missing something obvious, as I am an inexperienced user.
However, I looked at all the places that I could find, and so far no answer has seemed to help me
thanks for your help!

Categories

Resources