Firstly it's my first post here so sorry for that.
I am doing a Udemy course Hibernate & JPA and i have problem here.
I mean Im doing everything like a person from which am studing but a have problems to run a program.
I don't know how to deal with it.
I'm using Eclipse and for MySql is MySQL Workbench.
There is a my project -> click
and a guy's project from a Udemy -> click
When i want to run program a i have this problems
WARN - HHH000402: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
INFO - HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/ifinances]
INFO - HHH000046: Connection properties: {password=skills, user=infinite}
INFO - HHH000006: Autocommit mode: false
INFO - HHH000115: Hibernate connection pool size: 20 (min=1)
DEBUG - Initializing Connection pool with 1 Connections
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.infiniteskills.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
at com.infiniteskills.data.HibernateUtil.<clinit>(HibernateUtil.java:11)
at com.infiniteskills.data.Application.main(Application.java:12)
Caused by: java.sql.SQLException: The server time zone value '?rodkowoeuropejski czas letni' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specific time zone value if you want to utilize time zone support.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 15 more
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?rodkowoeuropejski czas letni' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specific time zone value if you want to utilize time zone support.
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:134)
at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2186)
at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2209)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1318)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
... 19 more
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.infiniteskills.data.Application.main(Application.java:12)
Caused by: java.lang.RuntimeException: There was an error building the factory
at com.infiniteskills.data.HibernateUtil.buildSessionFactory(HibernateUtil.java:22)
at com.infiniteskills.data.HibernateUtil.<clinit>(HibernateUtil.java:11)
... 1 more
Its my hibernate.cfg.xml file :
package com.infiniteskills.data;
import java.util.Date;
import org.hibernate.Session;
import com.infiniteskills.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
User user = new User();
user.setBirthDate(new Date());
user.setCreatedDate(new Date());
user.setCreatedBy("kevin");
user.setEmailAddress("kmb#yahoo.com");
user.setFirstName("Kevin");
user.setLastName("Bowersox");
user.setLastUpdatedBy("kevin");
user.setLastUpdatedDate(new Date());
session.save(user);
session.getTransaction().commit();
session.close();
}
}
hibernate.properties file :
hibernate.connection.username= infinite
hibernate.connection.password= skills
hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
log4j.properties file :
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=debug, stdout
Application.java file:
package com.infiniteskills.data;
import java.util.Date;
import org.hibernate.Session;
import com.infiniteskills.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
User user = new User();
user.setBirthDate(new Date());
user.setCreatedDate(new Date());
user.setCreatedBy("kevin");
user.setEmailAddress("kmb#yahoo.com");
user.setFirstName("Kevin");
user.setLastName("Bowersox");
user.setLastUpdatedBy("kevin");
user.setLastUpdatedDate(new Date());
session.save(user);
session.getTransaction().commit();
session.close();
}
}
HibernateUtil.java file:
package com.infiniteskills.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.infiniteskills.data.entities.User;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"There was an error building the factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
and my pom.xml file
<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>com.infiniteskills</groupId>
<artifactId>hibernate-course</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate-course</name>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
</project>
EDIT 1:
There is another problem ->
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.infiniteskills.data.entities.User
User.java File:
package com.infiniteskills.data.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_ID")
private Long userId;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="BIRTH_DATE")
private Date birthDate;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name="CREATED_DATE")
private Date createdDate;
#Column(name="CREATED_BY")
private String createdBy;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
Update hibernate.properties and add serverTimeZone property in JDBC connection string directly..
hibernate.connection.url=jdbc:mysql://localhost:3306/ifinances?serverTimezone=UTC
I have another problem with this project.
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.infiniteskills.data.entities.User
I added above a code from User.java
Related
JPA not working as expected even though it seems a simple JPQL call:
SELECT e FROM Employee e
...but, getting this exception (from system log after GET operation)...
Note the EL WARNING: "Model classes may not have been found during entity search"...
-
-
-
[EL Info]: 2018-09-19 12:21:37.142--ServerSession(301360221)--Thread(Thread[http-nio-8080-exec-1,5,main])--/file:/usr/local/apache-tomee-plume-7.0.5/webapps/MyRestSvc/WEB-INF/classes/_DB2JPA login successful
[EL Warning]: 2018-09-19 12:21:37.144--ServerSession(301360221)--Thread(Thread[http-nio-8080-exec-1,5,main])--Problem while registering MBean: java.lang.NullPointerException
[EL Warning]: 2018-09-19 12:21:37.156--Thread(Thread[http-nio-8080-exec-1,5,main])--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT e FROM Employee e].
[14, 22] The abstract schema type 'Employee' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1743)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1764)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:387)
at org.apache.openejb.persistence.JtaEntityManager.typedProxyIfNoTx(JtaEntityManager.java:382)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:454)
at aaa.bbb.ccc.war.MyRestSvc.get(MyRestSvc.java:42)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
-
-
-
Any ideas/suggestions to help solve this issue would be appreciated. Wondering if there is some incompatibilty with EclipseLink version 2.7.1 and how the model classes are generated via the Eclipse (photon) ide.
I'm using the db2sampl database that comes bundled with db2express-c...
Here is tomee.xml declaring the resource...
<?xml version="1.0" encoding="UTF-8"?>
<tomee>
<Resource id="jdbc/sample" type="javax.sql.DataSource">
driverClassName com.ibm.db2.jcc.DB2Driver
jdbcDriverType 4
url jdbc:db2://localhost:50000/SAMPLE
username db2inst1
password db2inst1-pwd
</Resource>
</tomee>
Here is the 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="DB2JPA">
<jta-data-source>jdbc/SAMPLE</jta-data-source>
<class>aaa.bbb.ccc.model.Department</class>
<class>aaa.bbb.ccc.model.Employee</class>
<class>aaa.bbb.ccc.model.Staff</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.level" value="FINE" />
</properties>
</persistence-unit>
</persistence>
Here are the model classes (created using Eclipse: Entities generated from tables)...
Employee.java...
package aaa.bbb.ccc.model;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the EMPLOYEE database table.
*
*/
#Entity
#Table(name="EMPLOYEE")
#NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(unique=true, nullable=false, length=6)
private String empno;
#Temporal(TemporalType.DATE)
private Date birthdate;
#Column(precision=9, scale=2)
private BigDecimal bonus;
#Column(name="\"COMM\"", precision=9, scale=2)
private BigDecimal comm;
#Column(nullable=false)
private short edlevel;
#Column(nullable=false, length=12)
private String firstnme;
#Temporal(TemporalType.DATE)
private Date hiredate;
#Column(length=8)
private String job;
#Column(nullable=false, length=15)
private String lastname;
#Column(length=1)
private String midinit;
#Column(length=4)
private String phoneno;
#Column(precision=9, scale=2)
private BigDecimal salary;
#Column(length=1)
private String sex;
//bi-directional many-to-one association to Department
#OneToMany(mappedBy="employee")
private List<Department> departments;
//bi-directional many-to-one association to Department
#ManyToOne
#JoinColumn(name="WORKDEPT")
private Department department;
public Employee() {
}
public String getEmpno() {
return this.empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public Date getBirthdate() {
return this.birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public BigDecimal getBonus() {
return this.bonus;
}
public void setBonus(BigDecimal bonus) {
this.bonus = bonus;
}
public BigDecimal getComm() {
return this.comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
public short getEdlevel() {
return this.edlevel;
}
public void setEdlevel(short edlevel) {
this.edlevel = edlevel;
}
public String getFirstnme() {
return this.firstnme;
}
public void setFirstnme(String firstnme) {
this.firstnme = firstnme;
}
public Date getHiredate() {
return this.hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getMidinit() {
return this.midinit;
}
public void setMidinit(String midinit) {
this.midinit = midinit;
}
public String getPhoneno() {
return this.phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
public BigDecimal getSalary() {
return this.salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getSex() {
return this.sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public List<Department> getDepartments() {
return this.departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
public Department addDepartment(Department department) {
getDepartments().add(department);
department.setEmployee(this);
return department;
}
public Department removeDepartment(Department department) {
getDepartments().remove(department);
department.setEmployee(null);
return department;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
Department.java...
(removed for space - can provide on request)
Staff.java...
(removed for space - can provide on request)
This is the REST service - just a GET method (for simplicity)...
package aaa.bbb.ccc.war;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import aaa.bbb.ccc.model.Employee;
#Stateless
#Path("/employeeList")
public class MyRestSvc {
#PersistenceContext(unitName = "DB2JPA")
EntityManager em;
#Context
UriInfo uriInfo;
public MyRestSvc() {
}
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> get(#Context javax.servlet.http.HttpServletRequest request) {
em.getEntityManagerFactory().getCache().evictAll(); // Invalidate all objects in the cache
List<Employee> eList = null;
try {
eList = em.createQuery("SELECT e FROM Employee e").getResultList();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return eList;
}
}
Here is the log on Tomee startup...
(removed for space - can provide on request)
Here is the system log ouput/reaction to GET operation...
[EL Info]: 2018-09-19 07:05:43.756--ServerSession(174651846)--Thread(Thread[http-nio-8080-exec-1,5,main])--EclipseLink, version: Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f
[EL Fine]: 2018-09-19 07:05:43.765--Thread(Thread[http-nio-8080-exec-1,5,main])--Detected database platform: org.eclipse.persistence.platform.database.DB2Platform
[EL Config]: 2018-09-19 07:05:43.777--ServerSession(174651846)--Connection(393909340)--Thread(Thread[http-nio-8080-exec-1,5,main])--connecting(DatabaseLogin(
platform=>DatabasePlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
[EL Config]: 2018-09-19 07:05:43.778--ServerSession(174651846)--Connection(935474207)--Thread(Thread[http-nio-8080-exec-1,5,main])--Connected: jdbc:db2://localhost:50000/SAMPLE
User: db2inst1
Database: DB2/LINUXX8664 Version: SQL10055
Driver: IBM Data Server Driver for JDBC and SQLJ Version: 4.21.29
[EL Config]: 2018-09-19 07:05:43.778--ServerSession(174651846)--Connection(247275895)--Thread(Thread[http-nio-8080-exec-1,5,main])--connecting(DatabaseLogin(
platform=>DB2Platform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
[EL Config]: 2018-09-19 07:05:43.791--ServerSession(174651846)--Connection(1852461265)--Thread(Thread[http-nio-8080-exec-1,5,main])--Connected: jdbc:db2://localhost:50000/SAMPLE
User: db2inst1
Database: DB2/LINUXX8664 Version: SQL10055
Driver: IBM Data Server Driver for JDBC and SQLJ Version: 4.21.29
[EL Info]: 2018-09-19 07:05:43.796--ServerSession(174651846)--Thread(Thread[http-nio-8080-exec-1,5,main])--/file:/usr/local/apache-tomee-plume-7.0.5/webapps/MyRestSvc/WEB-INF/classes/_DB2JPA login successful
[EL Warning]: 2018-09-19 07:05:43.799--ServerSession(174651846)--Thread(Thread[http-nio-8080-exec-1,5,main])--Problem while registering MBean: java.lang.NullPointerException
[EL Warning]: 2018-09-19 07:05:43.806--Thread(Thread[http-nio-8080-exec-1,5,main])--The collection of metamodel types is empty. Model classes may not have been found during entity search for Java SE and some Java EE container managed persistence units. Please verify that your entity classes are referenced in persistence.xml using either <class> elements or a global <exclude-unlisted-classes>false</exclude-unlisted-classes> element
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT e FROM Employee e].
[14, 22] The abstract schema type 'Employee' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1743)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:387)
at org.apache.openejb.persistence.JtaEntityManager.proxyIfNoTx(JtaEntityManager.java:375)
at org.apache.openejb.persistence.JtaEntityManager.createQuery(JtaEntityManager.java:329)
at aaa.bbb.ccc.war.MyRestSvc.get(MyRestSvc.java:40)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:191)
at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:102)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:205)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:186)
at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:252)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:212)
at org.apache.openejb.util.proxy.ProxyEJB$Handler.invoke(ProxyEJB.java:74)
at aaa.bbb.ccc.war.MyRestSvc$$LocalBeanProxy.get(aaa/bbb/ccc/war/MyRestSvc.java)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.performInvocation(OpenEJBEJBInvoker.java:95)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:191)
at org.apache.openejb.server.cxf.rs.OpenEJBEJBInvoker.invoke(OpenEJBEJBInvoker.java:68)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101)
at org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:64)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:96)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267)
at org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:253)
at org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.openejb.server.httpd.EEFilter.doFilter(EEFilter.java:65)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.tomee.catalina.OpenEJBSecurityListener$RequestCapturer.invoke(OpenEJBSecurityListener.java:97)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.1.v20171221-bd47e8f): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [SELECT e FROM Employee e].
[14, 22] The abstract schema type 'Employee' is unknown.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:347)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:278)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:163)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:140)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1741)
... 71 more
-
-
-
pom.xml...
(removed for space - can provide on request)
Environment info...
java 10
EclipseLink (2.7.1)
Dockerized Db2express-c
apache-tomee-7.0.5-plume
It seems there was an incompatibility with EclipseLink 2.7.1, somehow. When I changed to use EclipseLink 2.7.2, the issue disappeared. Thanks to all for comments, suggestions.
I took a hint from this posting:
https://www.eclipse.org/forums/index.php/t/1092642/
which referenced this bug:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=532882
<!--does not work...
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.1</version>
</dependency>
-->
<!-- works as expected...-->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.2</version>
</dependency>
Hi I am currently learning Hibernate and I am stuck on a problem where I am trying to override the column name from address to home address and office address. I commented out all office-address code, but the column in database are still "CITY_NAME", "STREET_NAME" and etc.
Could someone please explain this, thanks.
Address.java
package org.zm.javabrain.dto;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
#Column(name="STREET_NAME")
private String stree;
#Column(name="CITY_NAME")
private String city;
#Column(name="STATE_NAME")
private String state;
#Column(name="ZIP_NAME")
private String zip;
public String getStree() {
return stree;
}
public void setStree(String stree) {
this.stree = stree;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
this is UserDetails.java
package org.zm.javabrain.dto;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity // change the name of the entity
#Table(name="USER_DETAILS") // change the name of the table
public class UserDetails implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String username;
private Date joinedDate;
private String description;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="street",column=#Column(name="HOME_STREET_NAME")),
#AttributeOverride(name="city",column=#Column(name="HOME_CITY_NAME")),
#AttributeOverride(name="state",column=#Column(name="HOME_STATE_NAME")),
#AttributeOverride(name="zip",column=#Column(name="HOME_ZIP_NAME"))})
private Address homeAddress;
// #Embedded
// #AttributeOverrides({
// #AttributeOverride(name="street",column=#Column(name="OFFICE_STREET_NAME")),
// #AttributeOverride(name="city",column=#Column(name="OFFICE_CITY_NAME")),
// #AttributeOverride(name="state",column=#Column(name="OFFICE_STATE_NAME")),
// #AttributeOverride(name="zip",column=#Column(name="OFFICE_ZIP_NAME"))})
// private Address officeAddress;
//
// public Address getOfficeAddress() {
// return officeAddress;
// }
// public void setOfficeAddress(Address officeAddress) {
// this.officeAddress = officeAddress;
// }
public Date getJoinedDate() {
return joinedDate;
}
public void setJoinedDate(Date joinedDate) {
this.joinedDate = joinedDate;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
This is driver class
package org.zm.hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.zm.javabrain.dto.Address;
import org.zm.javabrain.dto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
Address addr = new Address();
addr.setCity("chicago");
addr.setState("IL");
addr.setStree("Michigen Ave");
addr.setZip("55414");
Address officeAddr = new Address();
officeAddr.setCity("minneapolis");
officeAddr.setState("Washington Ave");
officeAddr.setState("MN");
officeAddr.setZip("55455");
user.setUsername("11111");
user.setHomeAddress(addr);
// user.setOfficeAddress(officeAddr);
user.setJoinedDate(new Date());
user.setDescription("this is a description");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
I cannot tell you if Hibernate Session supports the AttributeOverride feature or not. The problem is, I guess, Hibernate is mixing two different technologies that are trying to solve the same problem, and that is confusing for new users trying to learn. Hibernate can be used as
Legacy (Native) ORM , and
JPA (Java Persistence API) implementation
As I can see from your posted code example that you are using JPA annotations. All annotations, classes and properties having the package structure of javax.persistence are JPA specific. So my advice is, either configure your persistence the Hibernate way or the JPA way, and don't mix.
If you want to map your entities the JPA way, do the following:
Put your configuration information in the file persistence.xml instead of in the hibernate.cfg.xml. The file should be under META-INF folder of your source directory. If you are using Maven put it under src/main/resources/META-INF directory. The file should look like:
<persistence 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"
version="2.1">
<persistence-unit name="yourPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>org.zm.javabrain.dto.UserDetails</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="..." />
<property name="javax.persistence.jdbc.url" value="..." />
<property name="javax.persistence.jdbc.user" value="..." />
<property name="javax.persistence.jdbc.password" value="..." />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>
replace the ... with correct database information.
In your test class (HibernateTest) do the following instead of SessionFactory / Session:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("yourPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit;
em.close();
emf.close();
You can also read:
Hibernate User Guide
Java Persistence API Tutorials
JPA 2.1 Specification
Hopefully, it helps.
I have gone through most of the similar issues posted here and the solution found there was to use javax.persistence.Entity import instead of org.hibernate.annotations.Entity.
I have used the correct import but still getting org.hibernate.MappingException
I am using mysql-connector-java version 6.0.5 with hibernate-core version 5.2.6.Final and hibernate-annotations version 3.5.6-Final
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.myApp.data.entities.User
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1627)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.myApp.data.Application.main(Application.java:26)
The pom.xml is as follows:
<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>com.myApp</groupId>
<artifactId>hibernate-course</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate-course</name>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.22</version>
</dependency>
</dependencies>
</project>
The following is my main class Application.java
package com.myApp.data;
import java.util.Date;
import org.hibernate.Session;
import com.myApp.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
User user = new User();
user.setBirthDate(new Date());
user.setCreatedBy("Smith");
user.setCreatedDate(new Date());
user.setEmailAddress("david_cfd#gmail.com");
user.setFirstName("David");
user.setLastName("Copperfield");
user.setLastUpdatedBy("david");
user.setLastUpdatedDate(new Date());
session.save(user);
session.close();
}
}
User Entity class
package com.myApp.data.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="finances_user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_ID")
private Long userId;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="BIRTH_DATE")
private Date birthDate;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name="CREATED_DATE")
private Date createdDate;
#Column(name="CREATED_BY")
private String createdBy;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
Hibernate SessionFactory Configuration class
package com.myApp.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"There was an error building the factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
and finally hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.url">jdbc:mysql://localhost:3306/ifinances?useSSL=false</property>
<property name="connection.username">infinite</property>
<property name="connection.password">skills</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping class="com.myApp.data.entities.User"/>
</session-factory>
</hibernate-configuration>
I checked the same thing using hibernate.properties instead of hibernate.cfg.xml by using configuration.addAnnotatedClass(User.class); and It compiled and executed with out any exception.
Found the solution. The above code will work fine in Hibernate 4.3.6 but problem is when working with Hibernate 5. The problem is with the following code:
return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build());
The problem is when you pass the StandardServiceRegistryBuilder as an argument inside buildSessionFactory(). When you do this the configuration loose all mapping information that is acquired through configuration.configure(); statement.
That is why the code worked fine when using hibernate.properties file (which doesnt use configuration.configure() ) but caused an exception when using hibernate.cfg.xml.
When using hibernate.cfg.xml
When using hibernate xml configuration method, you can simply return the sessionFactory that uses a no-arg buildSessionFactory() method.
The actual code the works (using hibernate.cfg.xml)
Issue solved!
package com.myApp.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.myApp.data.entities.User;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
/*return configuration
.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build()); -- does not work while using hibernate.cfg.xml, but works with hibernate.properties*/
return configuration
.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"There was an error building the factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Thanks for all who helped!
try using AnnotationConfiguration instead of Configuration.
Configuration configuration = new AnnotationConfiguration();
I am trying to use Hibernate on my project << all sources if wanted, I try to create and save an object player on startup, I get the following error:
START SCRIPT!
org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.util.Date centaurus.domain.User.created] by reflection for persistent property [centaurus.domain.User#created] : User{id=0, email='test', created=Wed Jun 08 13:06:53 BST 2016}
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
at org.hibernate.property.access.spi.GetterFieldImpl.getForInsert(GetterFieldImpl.java:58)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getPropertyValuesToInsert(AbstractEntityTuplizer.java:521)
at org.hibernate.tuple.entity.PojoEntityTuplizer.getPropertyValuesToInsert(PojoEntityTuplizer.java:228)
at org.hibernate.persister.entity.AbstractEntityPersister.getPropertyValuesToInsert(AbstractEntityPersister.java:4701)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:254)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
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:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at centaurus.service.player.PlayerDAOimpl.saveUser(PlayerDAOimpl.java:32)
at centaurus.Dbmaintain.start(Dbmaintain.java:25)
at restx.factory.Factory.start(Factory.java:846)
at restx.RestxMainRouterFactory.build(RestxMainRouterFactory.java:450)
at restx.RestxMainRouterFactory.newInstance(RestxMainRouterFactory.java:70)
at restx.servlet.RestxMainRouterServlet.init(RestxMainRouterServlet.java:74)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:519)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:331)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:747)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:706)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:492)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerCollection.doStart(HandlerCollection.java:229)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:277)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at restx.server.JettyWebServer.start(JettyWebServer.java:109)
at restx.server.JettyWebServer.startAndAwait(JettyWebServer.java:114)
at centaurus.AppServer.main(AppServer.java:30)
Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field centaurus.domain.User.created to centaurus.domain.User
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:379)
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)
... 40 more
2016-06-08 13:06:53,232 [main ] [ ] INFO restx.monitor.MetricsConfiguration - registering Metrics JVM metrics
I have stepped through my program and it seems to have a valid object passed the the hibernate save function, and somewhere inside it throws an error. I have tried removing the created field, at which point it then complains about a string field with the same error, trying to set it as a Player object itself.
here is my DAOimpl.class
package centaurus.dao.user;
import centaurus.domain.User;
import centaurus.service.HibernateUtils;
import restx.factory.Component;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.inject.Named;
import java.util.List;
#Component
public class UserDAOimpl implements UserDAO {
private static HibernateUtils hibernateUtils;
public UserDAOimpl(#Named("HibernateUtils") HibernateUtils hibernateUtils) {
this.hibernateUtils = hibernateUtils;
}
public User saveUser(User user){
Session session = hibernateUtils.getFactory().openSession();
Transaction tx = null;
Integer playerID = null;
try{
tx = session.beginTransaction();
//playerID = (Integer) session.save(user);
session.save(user);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return user;
}
public User getUser(int playerId){
Session session = hibernateUtils.getFactory().openSession();
try{
User user = (User)session.get(User.class, playerId);
return user;
}catch (HibernateException e) {
}finally {
session.close();
}
return null;
}
public List<User> getUsers(){
Session session = hibernateUtils.getFactory().openSession();
List<User> list = null;
try{
list = session.createCriteria(User.class).list();
}catch (HibernateException e) {
}finally {
session.close();
}
return list;
}
}
I have googled and googled and tried as many hibernate tutorials as i can find and I still have this issue. I don't understand why hibernate is trying to set a field as an object, I have my annotations.
incase its wanted here is my domain object player:
package centaurus.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
#Entity
#Table(name="users")
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="USER_ID")
private int id = 0;
#Column(name="EMAIL")
private String email = "";
#Column(name="CREATED")
private Date created = null;
public User(){
Calendar cal = Calendar.getInstance();
this.created = cal.getTime();
};
public User(int id, String email, Date created) {
this.id = id;
this.email = email;
this.created = created;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", email='" + email + '\'' +
", created=" + created +
'}';
}
}
and here is the calling class:
package centaurus;
import centaurus.dao.user.UserDAO;
import centaurus.domain.User;
import restx.factory.AutoStartable;
import restx.factory.Component;
import javax.inject.Named;
#Component
public class DBMaintain implements AutoStartable{
private UserDAO userDAO;
public DBMaintain(#Named("UserDAOimpl") UserDAO userDAO) {
this.userDAO = userDAO;
}
public void start(){
System.out.println("START SCRIPT!");
//test
User p = new User();
p.setEmail("test");
userDAO.saveUser(p);
}
}
Please does anyone know how to solve this issue, thanks.
EDIT: (added sql)
CREATE TABLE Users(
USER_ID int NOT NULL AUTO_INCREMENT,
CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
EMAIL varchar(45) DEFAULT NULL,
PRIMARY KEY (USER_ID)
);
EDIT added hibernate config
/src/main/resources/hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/andromeda</property>
<property name="hibernate.connection.username">api</property>
<property name="hibernate.connection.password">apipassword</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">1</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="centaurus.domain.User"/>
</session-factory>
</hibernate-configuration>
Not sure if this is the answer but we will see!
Try replacing
CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP
with
CREATED DATETIME DEFAULT CURRENT_DATETIME,
See the difference between Timestamp and Datetime in SQL is TIMESTAMP values are converted from the current time zone to UTC for storage, and converted back from UTC to the current time zone for retrieval. (This occurs only for the TIMESTAMP data type, not for other types such as DATETIME.)
If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored.
TimeStamp MySQL
While DATETIME represents a date (as found in a calendar) and a time (as can be observed on a wall clock),
Since you cannot store Java Date into a SQL TIMESTAMP object, either change the SQL TIMESTAMP to DATETIME or change the
private Date created;
to
private Timestamp created;
//And convert your Date to TimeStamp
public User(){
Date date = new Date();
created = new Timestamp(date .getTime());
}
Hope this helps!
remove the User class from the package centaurus
why?
On AppServer.main you have:
System.setProperty("restx.app.package", "centaurus");
this will make the restx recompile everything that's inside centaurus package and use this recompiled class, but apparently hibernate is retrieving the fields from the original class, not from the recompiled one
Here is the stacktrace that really matters:
Caused by: java.lang.IllegalArgumentException: Can not set java.util.Date field centaurus.domain.User.created to centaurus.domain.User
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:379)
The JVM is throwing an Exception because it cannot use the Field (that was retrieved by hibernate from the original compilation) at the class User (that was loaded by restx from the restx compilation)
Hibernate cannot transform to joda DateTime out of the box. Try to annotate your column with
#Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
See here for reference.
Looks like it is a bug in this version of Hibernate
HHH-10618
Try to use another one.
Your date field has to be annotated as follows:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "creation", updatable = false, length = 19)
public Date getCreation() {
return this.creation;
}
public void setCreation(Date creation) {
this.creation = creation;
}
Be sure to rename column and name of the filed to match your project.
I am trying to learn hibernate and i'm having a problem with hibernate annotations, the thing is that hibernate doesn't seam to recognise my entity User
package com.mycompanyname.myapp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="FINANCES_USER")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_ID")
private Long userId;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="BIRTH_DATE")
private Date birthDate;
#Column(name="EMAIL_ADDRESS")
private String emailAddress;
#Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
#Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
#Column(name="CREATED_DATE")
private Date createdDate;
#Column(name="CREATED_BY")
private String createdBy;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
}
this is my main
package com.mycompanyname.myapp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.MetadataSources;
import com.mycompanyname.myapp.User;
public class Application {
public static void main(String[] args) {
// A SessionFactory is set up once for an application!
SessionFactory sessionFactory =null;
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
//session.close();
}
}
this is my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="HibernateUtil">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">database</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/financialanalysis</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<mapping class="com.mycompanyname.myapp.User"/>
</session-factory>
</hibernate-configuration>
this exception keeps popping out
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.mycompanyname.myapp.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1096)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1443)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.mycompanyname.myapp.Application.main(Application.java:32)
so what am i doing wrong ?
I think there is an issue with the way you configure SessionFactory. I created a sample application based on the source code you have provided. I suspect there is something wrong with this line.
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
So I would take a different approach to configure session factory like this.
SessionFactory sessionFactory =null;
try {
Configuration configuration = new Configuration();
configuration.configure();
final ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(registry);
}
catch (Exception e) {
e.printStackTrace();
sessionFactory.close();
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.getTransaction().commit();
User user1 = new User();
user1.setUserId((long)234);
session.save(user1);
session.close();
Looking at the source code configuration.configure() method also finds the default hibernate.cfg.xml file on the classpath as new StandardServiceRegistryBuilder().configure() does. With these configurations in place now you should be able to persist/load/update entities without any issue.
I tested this configuration with a quick and dirty sample application using Hibernate 4.0.
Just use this to build a session factory
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
It works for Hibernate 4 and Hibernate 5. This code has a deprecation in Hibernate 4, but this deprecation is removed in Hibernate 5.
configure your User class like-
Configuration cfg=new Configuration();
cfg.addAnnotatedClass(com.mycompanyname.myapp.User.class);
cfg.configure();
hope it help.