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!
Related
When trying to save Student using session, I get this error though I used
.addAnnotatedClass(Student.class)
in Configuration and used
<mapping class="com.hibernate_demo.models.Student"/>
in Hibernate.cfg.xml
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate_demo.models.Student
at org.hibernate.metamodel.model.domain.internal.MappingMetamodelImpl.entityPersister(MappingMetamodelImpl.java:589)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1450)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:36)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:30)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:632)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:625)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:620)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at jdk.proxy2/jdk.proxy2.$Proxy35.save(Unknown Source)
at com.hibernate_demo.application.CreateStudentDemo.main(CreateStudentDemo.java:24)
Student.java
package com.hibernate_demo.models;
import javax.persistence.*;
#Entity
#Table(name = "Student")
public class Student {
#Id
private long id;
#Column(name="first_name", nullable = false)
private String firstName;
#Column(name="last_name", nullable = false)
private String lastName;
#Column(name="email", nullable = false)
private String email;
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public Student() {}
public long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
'}';
}
}
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property
name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.hibernate_demo.models.Student"/>
</session-factory>
</hibernate-configuration>
CreateStudentDemo.java
package com.hibernate_demo.application;
import com.hibernate_demo.models.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CreateStudentDemo {
public static void main(String[] args) {
// Create Session Factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// Using session object to save Java object
try (factory; Session session = factory.getCurrentSession()) {
factory.openSession();
System.out.println("Creating new student object...");
Student tempStudent = new Student("Tomasz", "Jurek", "jur.tomasz13#gmail.com");
System.out.println("Begin transaction");
session.beginTransaction();
System.out.println("Saving student..");
session.save(tempStudent);
System.out.println("Commiting transaction");
session.getTransaction().commit();
System.out.println("Transaction commited");
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Hibernate-Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Beta3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
</project>
Soo I used Hibernate 6.0.0.3 Beta Version, I changed it to latest non beta build (5.6.4.Final) and it worked.
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 have created a PostgreSQL script just to insert a row in the customer table. The insert happens when my project is starting to run.
But it doesn't work because I'm getting the following error:
[EL Warning]: 2016-10-23 22:14:40.182--ServerSession(609762439)--?>Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at end of input
Position: 82 Error Code: 0 Call: INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, >Fax, Number) VALUES Query: DataModifyQuery(sql="INSERT INTO customer (id, Name, Adres, >PostalCode, City, Tel, Fax, Number) VALUES") [EL Warning]: 2016-10-23 22:14:40.183--ServerSession(609762439)-->Exception [EclipseLink-4002] (Eclipse Persistence Services - >2.5.2.v20140319-9ad6abd): >org.eclipse.persistence.exceptions.DatabaseException Internal Exception: org.postgresql.util.PSQLException: ERROR: syntax >error at or near "1"
Position: 2 Error Code: 0 Call: (1, 'Kantoor Snel Transport / Distributiecentrum', >'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92'); Query: DataModifyQuery(sql="(1, 'Kantoor Snel Transport / >Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, >'92');") [EL Info]: connection: 2016-10-23 22:15:02.917-->ServerSession(609762439)-->file:/C:/Users/yomac_000/workspace/.metadata/.plugins/org.eclipse.wst.ser>ver.core/tmp0/wtpwebapps/snel-transport/WEB-INF/classes/_snel-transport >logout successful
Here is the persistence.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="snel-transport" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>nl.cimsolutions.snel_transport.models.Orders</class>
<class>nl.cimsolutions.snel_transport.models.OrderLine</class>
<class>nl.cimsolutions.snel_transport.models.OrderList</class>
<class>nl.cimsolutions.snel_transport.models.Customer</class>
<class>nl.cimsolutions.snel_transport.models.Product</class>
<class>nl.cimsolutions.snel_transport.models.Category</class>
<class>nl.cimsolutions.snel_transport.models.Status</class>
<class>nl.cimsolutions.snel_transport.models.Truck</class>
<!-- <jta-data-source>java:app/snel-transport</jta-data-source> -->
<!-- <exclude-unlisted-classes>false</exclude-unlisted-classes> -->
<properties>
<property
name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
<property name="eclipselink.canonicalmodel.subpackage"
value="dev" />
<property name="javax.persistence.sql-load-script-source"
value="META-INF/sql/Customer2.sql" />
<property name="javax.persistence.schema-generation-target"
value="database" />
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/snel-transport" />
<property name="javax.persistence.jdbc.user" value="transport_user" />
<property name="javax.persistence.jdbc.password"
value="admin" />
<property name="javax.persistence.jdbc.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
And here is my PostgreSQL script:
INSERT INTO customer (id, Name, Adres, PostalCode, City, Tel, Fax, Number) VALUES
(1, 'Kantoor Snel Transport / Distributiecentrum', 'Zeugstraat', '2801JD', 'Gouda', 182512784, NULL, '92');
And here is how the Customer model looks like:
#Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(
name = "CustomerGenerator",
allocationSize = 1,
initialValue = 1)
#Id
#GeneratedValue(strategy = GenerationType.TABLE,
generator="CustomerGenerator")
private Long id;
private String name;
private String adres;
#Column(name="Number")
private String streetNumber;
#Column(name="PostalCode")
private String postalCode;
#Column(name="City")
private String city;
#Column(name="Tel")
private String tel;
#Column(name="Fax")
private String fax;
#OneToMany(mappedBy = "customer", targetEntity = Orders.class)
private List<Orders> orders;
public Customer() {
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "model.OrderLine[ id=" + id + " ]";
}
public String getName() {
return name;
}
public String getAdres() {
return adres;
}
public void setName(String name) {
this.name = name;
}
public void setAdres(String adres) {
this.adres = adres;
}
}
I have already tried using the PostgreSQL script in pgAdmin. And there the script works, but somehow it doesn't work in JPA.. Anyone got a clue how I can solve this problem?
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;
I try to run a basic application with hibernate and jpa, but now I'm stuck on this exception when running app...Here's the code and erro below:
java.lang.IllegalArgumentException: Not an entity: class pka.EclipseJPAExample.domain.Employee
at org.hibernate.ejb.metamodel.MetamodelImpl.entity(MetamodelImpl.java:158)
at org.hibernate.ejb.criteria.QueryStructure.from(QueryStructure.java:136)
at org.hibernate.ejb.criteria.CriteriaQueryImpl.from(CriteriaQueryImpl.java:177)
at pka.EclipseJPAExample.jpa.JpaTest.createEmployees(JpaTest.java:47)
at pka.EclipseJPAExample.jpa.JpaTest.main(JpaTest.java:33)
JpaTest.java:
public class JpaTest {
private EntityManager manager;
public JpaTest(EntityManager manager) {
this.manager = manager;
}
/**
* #param args
*/
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnit");
EntityManager manager = factory.createEntityManager();
JpaTest test = new JpaTest(manager);
EntityTransaction tx = manager.getTransaction();
tx.begin();
try {
test.createEmployees();
} catch (Exception e) {
e.printStackTrace();
}
tx.commit();
test.listEmployees();
System.out.println(".. done");
}
private void createEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
int numOfEmployees = manager.createQuery(query).getResultList().size();
if (numOfEmployees == 0) {
Department department = new Department("java");
manager.persist(department);
manager.persist(new Employee("Jakab Gipsz",department));
manager.persist(new Employee("Captain Nemo",department));
}
}
private void listEmployees() {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Employee> query = builder.createQuery(Employee.class);
query.from(Employee.class);
List<Employee> resultList = manager.createQuery(query).getResultList();
for (Employee next : resultList) {
System.out.println("next employee: " + next);
}
}
}
and persistence.xml:
....<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/testowa" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="enchantsql" />
<property name="hbm2ddl.auto" value="create" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>....
Could you point where is the problem?
EDIT:
I forgot to paste Employee class...so here it is below:
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToOne
private Department department;
public Employee() {}
public Employee(String name, Department department) {
this.name = name;
this.department = department;
}
public Employee(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", department="
+ department.getName() + "]";
}
}
As you can see it is mapped.
Make sure #Entity annotation in your entity. You also need to configure an entity in persistence.xml
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<class>pka.EclipseJPAExample.domain.Employee</class>
If you have numerous ENTITY classes in your application, adding an entry for every entity in "persistence.xml" won't be a good choice.
Instead, create your own data source bean using Custom AutoConfiguration.
Use LocalContainerEntityManagerFactoryBean inside dataSource bean Creation method.
Here, you need to define
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new
LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPackagesToScan("org.springframework.boot.entities");
This package is the location where all entity classes have been saved.
Thus no need to define every single entry for Entity classes at "persistence.xml".
Prefer Spring-based Scanning.