Hibernate DAO setting object value as object - java

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.

Related

Problems with connection Hibernate to MySQL database

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

how to insert data one by one(each time program runs) in two table having one-to-many or many-to-one relationship in hibernate

my problem is that one row added successfully but when adding more data it shows an error given below. there is duplicate entry but i want to insert two laptop data for the same student. Im beginner in hibernate please guide me sir.
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:72)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3587)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:103)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:453)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1218)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:421)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at HibRelation.App.main(App.java:43)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
... 13 more
this is my student.java class
package HibRelation;
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
#Entity
public class Student
{
#Id
private int RollName;
private String Lname;
private int marks;
#OneToMany(mappedBy = "std")
private List<Laptop> laptop = new ArrayList<Laptop>();
public int getRollName() {
return RollName;
}
public void setRollName(int RollName) {
this.RollName = RollName;
}
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname = Lname;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public List<Laptop> getLaptop() {
return laptop;
}
public void setLaptop(List<Laptop> laptop) {
this.laptop = laptop;
}
#Override
public String toString() {
return "Student{" + "RollName=" + RollName + ", Lname=" + Lname + ",
marks=" + marks + '}';
}
}
and this is my Laptop.java class
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
#Entity
public class Laptop
{
#Id
private int id;
private String lname;
#ManyToOne
private Student std;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Student getStd() {
return std;
}
public void setStd(Student std) {
this.std = std;
}
}
and this is main logic App.java
public class App {
public static void main(String[] args)
{
Student student=new Student();
student.setRollName(102);
student.setLname("Dinu");
student.setMarks(95);
Laptop lap= new Laptop();
lap.setId(1);
lap.setLname("hp");
student.getLaptop().add(lap);
lap.setStd(student);
Configuration con=new Configuration().configure().addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);
StandardServiceRegistry registry=new StandardServiceRegistryBuilder().applySettings(con.getProperties()).build();
SessionFactory sfact=con.buildSessionFactory(registry);
Session session = sfact.openSession();
session.beginTransaction();
session.save(student);
session.save(lap);
session.getTransaction().commit();
}
}
Configuration.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedata</property>
<property name="hibernate.connection.username">root</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
The error is caused by the duplication of a primary key in laptop table. A primary key is a column which uniquely identifies any row of the table. if you want to insert more than once keep changing the id value of laptop.So when you run the program for next time change the value of Id. Like
laptop.setId(2); //or something else which is not present in the table already
if you want to add the same laptop into a new student then retrieve that laptop first for e.g
Laptop theLaptop = Session.get(Laptop.class,theId) // theId is the laptopid
student.addLaptop(theLaptop);
session.save(student);
I would suggest using #GeneratedValue annotation on field id. Your error is due to violation of primary key constraint on field id. You must avoid setting id while saving objects ideally.
If you want to add same laptop object every time to different students, initialize your fields in laptop entity class, add a constructor and call that constructor every time while setting a laptop for any student.

Field 'Id_employeer' doesn't have a default value

I don't understand why my app drop Exception "Field 'Id_employeer' doesn't have a default value".
Id_employeer is my primary key, when I try to save any information to my database I got that exception, but, when I try just to read info from DB it's working.
I read topic on StackOverflow, but I still don't understand the answers in my app. I'm working with Hibernate 5.2.11.
My CharacterInfo.hbm.xml:
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="CharacterInfo" table="employees">
<id name="Id" column="id_employeer">
<generator class="native"/>
</id>
<property name="Login" column="employeer_login"/>
</class>
</hibernate-mapping>
My HibernateUtility:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import java.util.List;
public class HibernateUtility {
SessionFactory sessionFactory;
public void saving(Object object){
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( object);
//session.save( new CharacterInfo().getLogin());
session.getTransaction().commit();
session.close();
}
public void reading(){
Session session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery("from CharacterInfo").list();
for ( CharacterInfo characterInfo : (List<CharacterInfo>) result ) {
System.out.println( "CharacterInfo (" + characterInfo.getLogin() + ") : " + characterInfo.getLogin() );
}
session.getTransaction().commit();
session.close();
}
protected void setUp() throws Exception {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure()
.build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
Next CharacterInfo class
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
#Entity
#Table( name = "employees")
public class CharacterInfo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id_employeer")
private int id ;
#Column(name = "employeer_Login")
private String login;
public CharacterInfo() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
main class
public class main {
public static void main(String args[]) throws Exception {
HibernateUtility hibernateUtility = new HibernateUtility();
CharacterInfo characterInfo = new CharacterInfo();
characterInfo.setId(1);
characterInfo.setLogin("PawJaw");
hibernateUtility.setUp();
hibernateUtility.saving(characterInfo);
}
}
and in the end Exception
ERROR: Field 'Id_employeer' doesn't have a default value Exception in
thread "main" org.hibernate.exception.GenericJDBCException: could not
execute statement at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at
org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at
org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2919)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3490)
at
org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:626)
at
org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:280)
at
org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:261)
at
org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:306)
at
org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at
org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
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:691)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:683) at
org.hibernate.internal.SessionImpl.save(SessionImpl.java:678) at
HibernateUtility.saving(HibernateUtility.java:17) at
main.main(main.java:10) Caused by: java.sql.SQLException: Field
'Id_employeer' doesn't have a default value at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at
com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at
com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 23 more
First of all, if you're using Hibernate annotations, you don't need to use Hibernate XML mapping files.
Your error is probably because of your database schema. The Id_employeer column is not auto-increment.

why this String desc variable not get inserted to the database in hibernate

I am a newbie to hibernate framework. I following a tutorial series available on the this link. Here is my model class
package kasun.hibernate.moreAnnotations;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="UserDetailsMoreAnn")
public class UserDetailsMoreAnnotations {
private int id;
private String name;
private String address;
private Date date;
private String desc;
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
// public String getDesc() {
// return desc;
// }
// public void setDesc(String desc) {
// this.desc = desc;
// }
}
and this is my Service method
package kasun.hibernate.moreAnnotations;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ServiceMethod {
public static void main(String[] args) {
UserDetailsMoreAnnotations objct= new UserDetailsMoreAnnotations();
objct.setName("Kalanka");
objct.setId(7);
objct.setAddress("Kuliyapitiya");
objct.setDate(new Date()); // provide the current date
// objct.setDesc("Younger Brother");
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session session= sessionFactory.openSession();
session.beginTransaction();
session.save(objct);
session.getTransaction().commit();
}
}
and this is my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!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.driver_class">org.hsq/ldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost/TestDB</property> -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateTesting1</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- 5) for the kasun.hibernate.moreAnnotations package -->
<mapping class="kasun.hibernate.moreAnnotations.UserDetailsMoreAnnotations" />
</session-factory>
</hibernate-configuration>
Above code runs without errors. The problem I encounter is that when I uncomment the lines
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
in my model class and set a value to desc by uncommenting the line
objct.setDesc("Younger Brother"); in the Service Method
I got a error as Unable to execute command [alter table UserDetailsMoreAnn add column desc varchar(255)] and it says that You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc varchar(255)' at line 1. What I am doing wrong? Can anyone help me to fix this.Thanks in advance
DESC is a reserved keyword in MySQL and cannot be used for field name. Try renaming to Description or something. :)
You can also annotate the field, but must use brackets or escaped quotes:
#Column(name = "[DESC]")
public String getDesc() {
or
#Column(name = "\"DESC\"")
public String getDesc() {
list of reserved words for MySQL 5.7: https://dev.mysql.com/doc/refman/5.7/en/keywords.html
desc is keyword in sql. You should use back tick character(`).
Here i cannot use back tick since stack overflow take it as code sample.
So here i use single quotes. 'desc' varchar(255) instead of desc varchar(255) in database. Using back tick symbol, we can use all reserved keyword in mysql
For back tick, refer https://superuser.com/questions/254076/how-do-i-type-the-tick-and-backtick-characters-on-windows
For entity mapping, refer http://www.mkyong.com/hibernate/how-to-use-database-reserved-keyword-in-hibernate/

Hibernate Unknown Entity error with SQL Server 2012

I am new to Hibernate, I am trying to connect it to SQL Server 2012.
I am trying to apply the hello world example in this topic
http://www.java2blog.com/2013/01/hibernate-hello-world-example-in-eclipse.html
It wasn't working at the beginning, but after search in Stack Overflow, I successfully get it connected to SQL Server 2012.
But I am still having an issue in mapping between my created class "User" with the database.
Here is my Configuration file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name = "hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name = "hibernate.connection.url">jdbc:sqlserver://KAREEM-LAPTOP;databaseName=Hibernate;instanceName=SQLEXPRESS;</property>
<property name = "hibernate.connection.username">sa</property>
<property name = "hibernate.connection.password">DFKI123</property>
<property name = "hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="org.arpit.javapostsforlearning.User" table="User"></mapping>
</session-factory>
</hibernate-configuration>
The User Class
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity(name="User")
#Table(name = "User")
public class User {
#Id
int userId;
#Column(name="User_Name")
String userName;
#Column(name="userMessage")
String userMessage;
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;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
Hibernate Main Class
package org.arpit.javapostsforlearning;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.annotations.*;
import org.hibernate.service.ServiceRegistry;
//import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args) {
Configuration configuration=new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf=configuration.buildSessionFactory(sr);
User user1=new User();
user1.setUserId(1);
user1.setUserName("Arpit");
user1.setUserMessage("Hello world from arpit");
User user2=new User();
user2.setUserId(2);
user2.setUserName("Ankita");
user2.setUserMessage("Hello world from ankita");
Session ss=sf.openSession();
ss.beginTransaction();
//saving objects to session
ss.save(user1);
ss.save(user2);
ss.getTransaction().commit();
ss.close();
}
}
It is working fine and I got an info that Schema export complete
But after that I got an error:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.arpit.javapostsforlearning.User
I have tried to follow several topic talking about the same issue, but no one worked with me, all topics were related to annotations but I did all of their recommendations without any hope.
I tried also to add Mapping section into the configuration file as per this article
Hibernate unknown entity error when saving new object
but it didn't work too,
What might cause this issue?
Try to change from create to update on this line:
<property name="hbm2ddl.auto">create</property>
#Entity shouldn't have any parameter as shown below:
#Entity
#Table(name = "User")
public class User {
Also, make sure that the table name in the database is exactly the same as you declared inside annotations. I hope you can solve it this way.

Categories

Resources