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.
Related
i'm sorry if you will consider this post as duplicated, but i couldn't find and answer for my problem. Maybe you can help me) Thanks.
"
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#536f2a7e'
***Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.javabrains.UserDetails
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 org.javabrains.Main.main(Main.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Main.java
package org.javabrains;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* Created by roysez on 26.03.2017.
*/
public class Main {
public static void main(final String[] args) throws Exception{
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Sergiy");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
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>
<!-- Database connection settings -->
<property name='connection.driver_class'>com.mysql.jdbc.Driver</property>
<property name='connection.url'>jdbc:mysql://localhost:3306/hibernate</property>
<property name='connection.username'>root</property>
<property name='connection.password'>sergio161098</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>
<!-- Echo all executed SQL to stdout -->
<property name='show_sql'>true</property>
<property name="hbm2ddl.auto">create</property>
<!-- Mapping files -->
<mapping class="org.javabrains.UserDetails"/>
</session-factory>
</hibernate-configuration>
UserDetails.java
package org.javabrains;
import org.hibernate.annotations.Entity;
import javax.persistence.Id;
/**
* Created by roysez on 26.03.2017.
*/
#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) {
this.userName = userName;
}
}
I don't know what to do, try all solutions but any of them can't help
If you are intending to use the JPA API, I think you should change line 3 of UserDetails.java:
import org.hibernate.annotations.Entity;
to use JPA annotations:
import javax.persistence.Entity;
Hibernate documentation says org.hibernate.annotations.Entity does not replace javax.persistence.Entity, it just allows to configure additional features.
I think you should put all correct annotations: #Table,#Column,#GeneratedValue etc. in UserDetails.java.
And not forget to have some schema on MySQL server.
And if you are using Hibernate 5 you must use javax.persistence. package for annotations
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.
I create a small java class for hibernate but its gives an exception.I'm using Hibernate 5.0.2 and java 8 on ubuntu 14.04.
My classes and Hibernate configuration files is as follows.Hope someone can help me to find a solution to this.
This is the exception that occurs.
java.lang.NullPointerException
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.getResources(ClassLoaderServiceImpl.java:173)
at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:348)
at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.loadJavaServices(ClassLoaderServiceImpl.java:324)
at org.hibernate.integrator.internal.IntegratorServiceImpl.<init>(IntegratorServiceImpl.java:40)
at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:212)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:119)
at com.gim.gimpro.HibernateTest.setUp(HibernateTest.java:43)
at com.gim.gimpro.HibernateTest.main(HibernateTest.java:18)
Here is my code
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.gim.hibe.UserDetails;
public class HibernateTest {
private SessionFactory sessionFactory;
public static void main(String[] args){
HibernateTest hibernateTest=new HibernateTest();
try {
hibernateTest.setUp();
hibernateTest.save();
} catch (Exception e) {
e.printStackTrace();
}
}
void save(){
UserDetails userDetails=new UserDetails();
userDetails.setUserId(1);
userDetails.setUserName("Gihan");
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( userDetails );
session.getTransaction().commit();
session.close();
}
protected void setUp() throws Exception {
sessionFactory = new Configuration().configure() .buildSessionFactory();
}
}
UserDetails class
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "USER_DETAILS")
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) {
this.userName = userName;
}
}
Hibernate Configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 5.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/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="com.gim.hibe.UserDetails"/>
</session-factory>
</hibernate-configuration>
This Exception can occur because of below 2 reasons:
Please check if package com.gim.hibe for UserDetails class is correct.
Also see if Hibernate libraries are properly included in the classpath.
I have a problem trying to create a query from a Struts2 application with Hibernate and DB2 database. It throws me an Exception:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
ClienteCRM is not mapped
ClienteCRM is not mapped [FROM ClienteCRM WHERE nombre LIKE XXXX]
File: org/hibernate/hql/internal/ast/util/SessionFactoryHelper.java
Line number: 171
First of all this is my project tree:
I have this files:
Hibernate configuration file:
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.connection.driver_class">com.ibm.as400.access.AS400JDBCDriver</property>
<property name="hibernate.connection.url">jdbc:as400://10.10.10.131/sugarcrmak </property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pwd</property>
<property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
<mapping class="com.ak.exchange.model.dto.ClienteCRM" />
</session-factory>
Bean
package com.ak.exchange.model.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="accounts")
//#NamedQuery(name="ClienteCRM.buscarPorNombre", query="from ClienteCRM c where c.nombre like :nombre")
public class ClienteCRM implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="id")
private String id;
#Column(name="name")
private String nombre;
public ClienteCRM(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
DAO layer for ClienteCRM
package com.ak.exchange.model.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.ak.exchange.model.dto.ClienteCRM;
public class ClienteDAO {
protected Session session;
protected void openSession(){
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
session = sessionFactory.openSession();
}
protected void closeSession(){
session.close();
}
public List<ClienteCRM> buscarClientesCRMPorNombre (String aNombre){
this.openSession();
session.beginTransaction();
// Query query = session.getNamedQuery("ClienteCRM.buscarPorNombre");
// query.setParameter("nombre", "%" + aNombre + "%");
Query selectAll = session.createQuery("FROM ClienteCRM WHERE nombre LIKE " + aNombre);
#SuppressWarnings("unchecked")
List<ClienteCRM> tmpClientes = (List<ClienteCRM>) selectAll.list();
this.closeSession();
return tmpClientes;
}
}
As you can see, I've tried to create a query by using a NamedQuery (commented) and also creating from the DAO.
Any idea?
Thanks a lot
Put your hibernate.cfg.xml inside src/main/resources
Put your mapping files inside src/main/resources
Map your files like this:
<mapping resource="ClienteCRM.hbm.xml" />
It should work.
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.