Hibernate can't save entity without renaming - java

I have very strange problem and I can't understand it's reason.
I tried to save simple Object (Group.class) with only 1 field (#id groupName), getter and setter.
When I try to run my program, I have an exception:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Could not execute JDBC
batch update at
...
Caused by: java.sql.BatchUpdateException: 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 'Group (groupName) values
('Test')' at line 1
But if I specify the name of entity (different of Group) all works fine.
Could you please explain me what I've done wrong?
Code:
hibernate.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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.globallogic.dto.Group"></mapping>
</session-factory>
</hibernate-configuration>
import javax.persistence.*;
Group.class
#Entity //this doesn't work
//#Entity(name = "SomeName") // this works good
public class Group {
#Id
private String groupName;
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getGroupName() {
return groupName;
}
}
DataSender.class
public class DataSender {
private SessionFactory sessionFactory;
public DataSender() {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
}
public void sendData(Object... objects) {
Session session = sessionFactory.openSession();
if (session.isConnected()) {
System.out.println("ALL IS GOOD");
session.beginTransaction();
for (Object user: objects) {
session.persist(user);
}
System.out.println();
session.getTransaction().commit();
session.close();
System.out.println("Connection is closed");
}
sessionFactory.close();
}
}
Main.class
public class Main {
public static void main(String[] args) {
DataSender ds = new DataSender();
Group group = new Group();
group.setGroupName("Test");
ds.sendData(group);
}
}

Group is an SQL keyword, you'll need to quote your table name:
#Entity
#Table(name = "`Group`")
public class Group {
....

Related

Hibernate doesn't save entity

I'm really new to hibernate and try to understand how it works. But know I faced with the problem.
First of all, I have such mapping:
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Author() {
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
But then, when I tried to save this entitye with session.save(), hibernate showed me error like
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "author" violates not-null constraint
Failing row contains (null, hello!).
So I decided to notice, why hibernate doesn't increment the id automaticy and recognized that POSTGRESQL doesn't suppert annotation GenerationType.IDENTITY. So I changet it to the GenerationType.SEQUENCE. The error was gone, but entity wasn't saved.
So here's hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernate?useSSL=false
&serverTimezone=UTC</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="connection.username">postgres</property>
<property name="connection.password">4122</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="hibernate.entity.Author"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
Here's HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.build();
SessionFactoryBuilder sessionFactoryBuilder = metadata.getSessionFactoryBuilder();
return sessionFactoryBuilder.build();
}
public static SessionFactory getSessionFactory() {
if(sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
And here's the Main.java, where I call the hibernate functions:
public class Main {
public static void main(String[] args) {
try(Session session = HibernateUtil.getSessionFactory().openSession()) {
Transaction tx = session.beginTransaction();
Author author = new Author();
author.setName("hello!");
session.save(author);
tx.commit();
System.out.println(session.get(Author.class, 1L));
}
}
}
After program execution it prints me null and there is no entity in database:
If you know, what can be the problem, please tell me. I'd really apreciate it!
I think the reason is setter for id missing:
public long setId(long id) {
this.id = id;
}

How to create a generic DAO for CRUD methods

I'm trying to create a generic DAO for the basic CRUD methods so that I can reuse the code, but I really have no clue how to start.
I already have a DAO for every class, and they work perfectly.
I read lots of tutorial, and downloaded projects, but I can't adapt (or understand) it to my program.
Here is my class:
public class Cliente {
private String nombre, direccion, telefono, cuit;
private int codigo, codigoPostal;
private double saldo, deuda;
public Cliente(String nombre, String direccion, int codigoPostal, String telefono, String cuit) {
this.nombre = nombre;
this.direccion = direccion;
this.codigoPostal = codigoPostal;
this.telefono = telefono;
this.cuit = cuit;
this.saldo = 0;
this.deuda = 0;
}
public Cliente(){
}
//all the getters and setters
This is my GenericDAO that is not working
public class GenericDAO {
#Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
public <T> T save(final T o){
return (T) sessionFactory.getCurrentSession().save(o);
}
public void delete(final Object object){
sessionFactory.getCurrentSession().delete(object);
}
/***/
public <T> T get(final Class<T> type, final long id){
return (T) sessionFactory.getCurrentSession().get(type, id);
}
/***/
public <T> T merge(final T o) {
return (T) sessionFactory.getCurrentSession().merge(o);
}
/***/
public <T> void saveOrUpdate(final T o){
sessionFactory.getCurrentSession().saveOrUpdate(o);
}
public <T> List<T> getAll(final Class<T> type) {
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(type);
return crit.list();
}
}
My Class.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="principal.Cliente" table="Cliente">
<id name="codigo" column="codigo">
<generator class="identity" />
</id>
<property name="nombre" type="string" column="nombre"/>
<property name="direccion" type="string" column="direccion"/>
<property name="telefono" type="string" column="telefono"/>
<property name="cuit" type="string" column="cuit"/>
<property name="codigoPostal" type="int" column="cp"/>
<property name="saldo" type="double" column="saldo"/>
<property name="deuda" type="double" column="deuda"/>
</class>
</hibernate-mapping>
This is my HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
if (sessionFactory == null)
{
Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
And my hibernate.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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/basededatosprueba</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.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="mapeos/Cliente.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I'd appreciate if someone could explain how to make it work.
Solution by duffymo
Use the Spring Boot CrudRepository:
spring.io/guides/gs/accessing-data-jpa

org.hibernate.MappingException: Unknown entity

This question is different from the other questions on the same topic of MappingException: Unknown entity because I have this line in my hibernate config:
<mapping class="bbb.Students" />
My entity class is as follows:
package bbb;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Students")
public class Students implements java.io.Serializable {
private String id;
private String name;
private String number;
#Id
#Column(name = "ID", unique = true, nullable = false)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "NUMBER", nullable = false)
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
I have the database test and the table Students manually created.
The error is:
org.hibernate.MappingException: Unknown entity: bbb.Students
Exception in thread "main" org.hibernate.MappingException: Unknown entity: bbb.Students
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
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 bbb.App.main(App.java:39)
The Main class is as follows:
package bbb;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class App
{
public static void main( String[] args )
{
System.out.println("Hibernate one to one (Annotation)");
Configuration conf = new Configuration();
SessionFactory sf = conf.configure()
.buildSessionFactory(
new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties())
.build());
Session session = sf.openSession();
session.beginTransaction();
Students s = new Students();
s.setId("1");
s.setName("Joe");
s.setNumber("12345");
session.save(s);
session.getTransaction().commit();
System.out.println("Done");
}
}
The full hibernate.config is as follows:
<?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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="bbb.Students" />
</session-factory>
</hibernate-configuration>
Just imported your Students class in a Hibernate based project. Everything work fine. Before running the application, I created schema "test" manually. Post a class with the main method. Probably something is wrong in it.
Update:
Imported your's main method. The application still works. Can't reproduce an issue.
import bbb.Students;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
ourSessionFactory = new Configuration().
configure("hibernate.cfg.xml").
buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
Transaction transaction= session.beginTransaction();
Students student = new Students();
student.setName("Vasua");
student.setNumber("13");
student.setId("1");
session.save(student);
transaction.commit();
} finally {
session.close();
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernte Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:mysql://localhost/stack
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
root
</property>
<!-- DB schema will be updated if needed -->
<property name="hbm2ddl.auto">update</property>
<mapping class="bbb.Students"/>
</session-factory>
</hibernate-configuration>

Hibernate - java.lang.ClassCastException: com.SampleProjectDto.UserDetails cannot be cast to com.splwg.base.api.GenericPersistentEntity

I was trying to write my first Hibernate project, while running it I got this exception:
java.lang.ClassCastException: com.SampleProjectDto.UserDetails cannot be cast to com.splwg.base.api.GenericPersistentEntity
Table got created in the DB but values are not inserted in it.
Model class:
package com.SampleProjectDto;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails {
#Id
private int userId;
private String UserName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#(db_details)</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class ="com.SampleProjectDto.UserDetails"/>
</session-factory>
</hibernate-configuration>
Main Class:
package com.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
import com.SampleProjectDto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Somya");
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
ServiceRegistryBuilder srb = new ServiceRegistryBuilder().applySettings(cfg.getProperties());
SessionFactory sessionFactory = cfg.configure().buildSessionFactory(srb.buildServiceRegistry());
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Error Log:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" java.lang.ClassCastException: com.SampleProjectDto.UserDetails cannot be cast to com.splwg.base.api.GenericPersistentEntity
at org.hibernate.event.internal.COBOLCompatibleFlushEntityEventListener.onFlushEntity(COBOLCompatibleFlushEntityEventListener.java:136)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:225)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1127)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:325)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.hibernate.test.HibernateTest.main(HibernateTest.java:25)
Would appreciate any help on this!
I extended GenericPersistentEntity class, now its working fine.

Hibernate + PostgreSQL throws an Exception: Unknown entity

I write a java maven project for restful webservice using jersey + hibernate and having below error:
javax.servlet.ServletException: org.hibernate.MappingException:
Unknown entity: org.asad.dto.logindetail
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:419)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:
381)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:344)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:
221)
hibernate.cfg.xml File:
<?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.driver_class">org.postgresql.Drive</property>
<property
name="connection.url">jdbc:postgresql://localhost:5432/logindb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">project</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property
name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<propertyname="connection.driver_class">org.postgresql.Driver</property>
<!-- Names the annotated entity class -->
<mapping class="org.asad.dto.logindetail"/>
</session-factory>
</hibernate-configuration>
The table name is "logindetail".
Database Class:
#Entity
#Table (name = "logidetail") public class logindetail {
#Id
int userId;
String name;
String password;
public void setUserId(int i){
this.userId = i;
}
public int getUserId(){
return userId;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setPassword(String pass){
this.password = pass;
}
public String getPassword(){
return password;
}}
Main Class:
package org.asad.login.login.loginservice;
import java.util.ArrayList;
import javax.management.Query;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.asad.dto.logindetail;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configurationimport org.hibernate.classic.Session;
public class LoginService{
SessionFactory sessionFactory = null;
Session session = null;
public String getDatabaseUser(){
logindetail user = null;
String name=null;try{
sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
user = (logindetail)session.get(logindetail.class, 2);
name = user.getName();
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
return name;
}}
now this error is coming java.lang.NullPointerException
anyone can help me to eliminate this error i will b thankful :)
Can you check if you imported correct #Entity annotation.
As #Entity comes under two packages one is org.hibernate.annotations.Entity and other one with javax.persistence.Entity.
Use javax.persistence.Entity to annotate your entity beans. Don't import org.hibernate.annotations.Entity.

Categories

Resources