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;
Related
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.
I am trying to get a user based on their ID using this named query, however I keep getting an illegal argument exception. I've been looking at this code for awhile. Hopefully someone may catch something I might've missed.
This is my ORM
#Entity
#Table(name = "MYUSER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Myuser.findAll", query = "SELECT m FROM Myuser m"),
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
#NamedQuery(name = "Myuser.findByName", query = "SELECT m FROM Myuser m WHERE m.name = :name"),
#NamedQuery(name = "Myuser.findByPassword", query = "SELECT m FROM Myuser m WHERE m.password = :password"),
#NamedQuery(name = "Myuser.findByEmail", query = "SELECT m FROM Myuser m WHERE m.email = :email"),
#NamedQuery(name = "Myuser.findByTel", query = "SELECT m FROM Myuser m WHERE m.tel = :tel"),
#NamedQuery(name = "Myuser.findByAddress", query = "SELECT m FROM Myuser m WHERE m.address = :address"),
#NamedQuery(name = "Myuser.findBySecqn", query = "SELECT m FROM Myuser m WHERE m.secqn = :secqn"),
#NamedQuery(name = "Myuser.findBySecans", query = "SELECT m FROM Myuser m WHERE m.secans = :secans")})
public class Myuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "USERID")
private Integer userid;
#Column(name = "NAME")
private String name;
#Column(name = "PASSWORD")
private String password;
#Column(name = "EMAIL")
private String email;
#Column(name = "TEL")
private Integer tel;
#Column(name = "ADDRESS")
private String address;
#Column(name = "SECQN")
private String secqn;
#Column(name = "SECANS")
private String secans;
public Myuser() {
}
public Myuser(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTel() {
return tel;
}
public void setTel(Integer tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userid != null ? userid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Myuser)) {
return false;
}
Myuser other = (Myuser) object;
if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejbentity.Myuser[ userid=" + userid + " ]";
}
}
This is my user facade
#Stateless
public class MyuserFacade implements MyuserFacadeRemote {
#PersistenceContext(unitName = "EJBServer-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public MyuserFacade() {
//super(Myuser.class);
}
#Override
public Myuser getUser(int userID) {
Myuser aUser = new Myuser();
aUser = (Myuser)em.createNamedQuery("Myuser.findByUserid").setParameter("userid", userID).getResultList();
return aUser;
}
}
My 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="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!--<exclude-unlisted-classes>false</exclude-unlisted-classes>-->
<class>ejbentity.Myuser</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/EA"/>
<property name="javax.persistence.jdbc.password" value="test"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.user" value="test"/>
</properties>
</persistence-unit>
</persistence>
Error Log is given below:
java.lang.reflect.InvocationTargetException
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.glassfish.appclient.client.acc.AppClientContainer.launch(AppClientContainer.java:446)
at org.glassfish.appclient.client.AppClientFacade.main(AppClientFacade.java:166)
Caused by: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy266.getUser(Unknown Source)
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.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1135)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createNamedQuery(EntityManagerWrapper.java:522)
at stateless.MyuserFacade.getUser(MyuserFacade.java:62)
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.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4786)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:656)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:73)
at org.jboss.weld.ejb.SessionBeanInterceptor.aroundInvoke(SessionBeanInterceptor.java:52)
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.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:608)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
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.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4758)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4746)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:205)
... 19 more
Java Result: 1
Actual error:
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findByUserid not found.
Happens from:
#NamedQuery(name = "Myuser.findByUserid", query = "SELECT m FROM Myuser m WHERE m.userid = :userid"),
UPDATE:
From your persistence.xml:
<persistence-unit name="EJBEntityPU" transaction-type="RESOURCE_LOCAL">
Here you are using transaction-type="RESOURCE_LOCAL". So if you use it, then you are responsible for EntityManager.
Then you must have to follow (JPA Concepts: JPA 101)
You must use the EntityManagerFactory to get an EntityManager
The resulting EntityManager instance is a PersistenceContext/Cache
An EntityManagerFactory can be injected via the #PersistenceUnit
annotation only (not #PersistenceContext)
You are not allowed to use #PersistenceContext to refer to a unit of
type RESOURCE_LOCAL
You must use the EntityTransaction API to begin/commit around every
call to your EntityManger
Calling entityManagerFactory.createEntityManager() twice results in
two separate EntityManager instances and therefor two separate
PersistenceContexts/Caches.
It is almost never a good idea to have more than one instance of an
EntityManager in use (don't create a second one unless you've
destroyed the first)
Solution:
This is an example. you can follow the tutorial if you want to use RESOURCE_LOCAL.
Related Link:
DON'T USE JPA'S RESOURCE_LOCAL ON THE SERVER
Persistence unit as RESOURCE_LOCAL or JTA?
persistence.xml different transaction-type attributes
We got the same error and it was because the entities were missing in persistence.xml
In your persistence.xml is:
<persistence-unit name="EJBEntityPU"
but in your MyuserFacade you use:
#PersistenceContext(unitName = "EJBServer-ejbPU")
You should change that to:
#PersistenceContext(unitName = "EJBEntityPU")
I notice you have class ejbentity.Myuser in your persistence.xml. The class actually lives in a package structure consisting of one directory called "ejbentity"? The stacktrace suggests that your Myuser class with the NamedQuery annotations is not being found, which would be explained if your package structure is not being loaded as you expect.
I don't think that transaction-type has anything to do with #NamedQuery annotation.
This error
Caused by: java.lang.IllegalArgumentException: NamedQuery of name: Myuser.findAll not found.
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:355)
looks like an EclipseLink bug. Which version are you using ?
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;
}
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!
I am getting following exception at query.can you please tell mw whats wrong is in my code?
org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(Custom Loader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
at com.bdisys.promorphics.dao.impl.BlogDaoImpl.getTopBlogsQuesByDate(BlogDaoImpl.java:126)
at org.apache.jsp.Mydetails_jsp._jspService(Mydetails_jsp.java:935)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
at java.lang.Thread.run(Unknown Source)
Blog.java :
#SuppressWarnings("serial")
#Entity
#Table(name="blog")
public class Blog extends BaseDomain {
#Column(name="blog_title")
private String blogTitle;
#Column(name="blog_text",columnDefinition="TEXT")
private String blogText;
#Enumerated(EnumType.STRING)
#Column(name="blog_status")
private Status blogStatus;
#OneToOne
#JoinColumn(name="created_by", nullable=false)
private User createdBy;
#OneToOne
#JoinColumn(name="blog_category", nullable=false)
private BlogCategory blogCategory;
#Temporal(TemporalType.DATE)
#Column(name="created_date")
private Date createdDate;
#Column(name="likes")
private Long likes;
#Column(name="uploads")
private String uploads;
#Column(name="youtube_link")
private String youTubeLik;
#Column(name="moderator_comment")
private String moderatorComment;
#Lob
#Column(name="blog_description")
private String blog_desc;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public String getBlog_desc() {
return blog_desc;
}
public void setBlog_desc(String blog_desc) {
this.blog_desc = blog_desc;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogText() {
return blogText;
}
public void setBlogText(String blogText) {
this.blogText = blogText;
}
public Status getBlogStatus() {
return blogStatus;
}
public void setBlogStatus(Status blogStatus) {
this.blogStatus = blogStatus;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public BlogCategory getBlogCategory() {
return blogCategory;
}
public void setBlogCategory(BlogCategory blogCategory) {
this.blogCategory = blogCategory;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Long getLikes() {
return likes;
}
public void setLikes(Long likes) {
this.likes = likes;
}
public String getUploads() {
return uploads;
}
public void setUploads(String uploads) {
this.uploads = uploads;
}
public String getYouTubeLik() {
return youTubeLik;
}
public void setYouTubeLik(String youTubeLik) {
this.youTubeLik = youTubeLik;
}
public String getModeratorComment() {
return moderatorComment;
}
public void setModeratorComment(String moderatorComment) {
this.moderatorComment = moderatorComment;
}
}
Askquestions.java :
#SuppressWarnings("serial")
#Entity
#Table(name="askquestions")
public class Askquestions extends BaseDomain {
#Column(length = 100, name = "id_subscribers")
private String idSubscribers;
#Column(length = 100, name = "is_anonymous")
private String isAnonymous;
#Column(length = 100, name = "display_name")
private String displayName;
#Temporal(TemporalType.DATE)
#Column(length = 100, name = "created_on")
private Date createdQuesOn;
#Lob
#Column(name = "ask_question")
private String askQuestion;
#Column(length = 100, name = "ask_to_whom")
private String askToWhom;
#Lob
#Column(name="question_of_day")
private String questionOfDay;
#ManyToOne
#JoinColumn(name="ask_category")
private Askcategory askcategory;
#ManyToOne
#JoinColumn(name="users")
private User users;
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
public Askcategory getAskcategory() {
return askcategory;
}
public void setAskcategory(Askcategory askcategory) {
this.askcategory = askcategory;
}
public String getQuestionOfDay() {
return questionOfDay;
}
public void setQuestionOfDay(String questionOfDay) {
this.questionOfDay = questionOfDay;
}
public String getIdSubscribers() {
return idSubscribers;
}
public void setIdSubscribers(String idSubscribers) {
this.idSubscribers = idSubscribers;
}
public String getIsAnonymous() {
return isAnonymous;
}
public void setIsAnonymous(String isAnonymous) {
this.isAnonymous = isAnonymous;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAskQuestion() {
return askQuestion;
}
public void setAskQuestion(String askQuestion) {
this.askQuestion = askQuestion;
}
public String getAskToWhom() {
return askToWhom;
}
public void setAskToWhom(String askToWhom) {
this.askToWhom = askToWhom;
}
public Date getCreatedQuesOn() {
return createdQuesOn;
}
public void setCreatedQuesOn(Date createdQuesOn) {
this.createdQuesOn = createdQuesOn;
}
}
BlogDaoimpl Method:this query is not getting executed while other small queries are getting executed.why is it happening????
String sql = " select title , date from (select blog_title as title ,created_date as date from blog union select ask_question as title , created_on as date from askquestions ) as aa order by date desc";
SQLQuery query = getSession().createSQLQuery(sql);
return query.list();
hibrnate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- <property name="hibernate.connection.password">websitebdi</property>
<property name="hibernate.connection.url">jdbc:mysql://184.172.182.251:3306/bdiwebsite</property>
<property name="hibernate.connection.username">bdiwebsite</property> -->
<property name="hibernate.connection.password">MAYbdiSYS2008</property>
<property name="hibernate.connection.url">jdbc:mysql://115.119.114.10:3306/bdisystems</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
<!-- The maximum number of connections -->
<property name="hibernate.c3p0.max_size">20</property>
<!-- The minimum number of connections -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- Get a connection timeout , If you exceed this time , Throws an exception, in milliseconds -->
<property name="hibernate.c3p0.timeout">120</property>
<!-- The maximum number of PreparedStatement -->
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Every 120 seconds checking connection idle connection in the pool, the unit is in seconds -->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- When connection pooling connections inside out, look at the new C3P0 get the number of connections -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<!-- Always verify the connection -->
<property name="hibernate.c3p0.validate">true</property>
<!--
<property name="hibernate.c3p0.max_size">100</property>
<property name="hibernate.c3p0.min_size">0</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.timeout">100</property>
-->
<!-- Mapping Classes -->
<mapping class="com.bdisys.promorphics.domain.BlogCategory"/>
<mapping class="com.bdisys.promorphics.domain.Blog"/>
<mapping class="com.bdisys.promorphics.domain.Career"/>
<mapping class="com.bdisys.promorphics.domain.Partners"/>
<mapping class="com.bdisys.promorphics.domain.Askcategory"/>
<mapping class="com.bdisys.promorphics.domain.Askquestions"/>
<mapping class="com.bdisys.promorphics.domain.Askanswers"/>
</session-factory>
</hibernate-configuration>
Create a custom Dialect (extending MySQLDialect) and in your constructor add
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
public class MySQLDialect extends MySQLDialect {
public AGOSQLServerDialect() {
super();
registerHibernateType(Types.LONGVARCHAR, TextType.INSTANCE.getName());
}
}
Remember to change dialect class into Hibernate config file
<property name="hibernate.dialect">path.to.YourDialect</property>