I am trying to persist my java object to Mysql database. But i am facing the following error.
ClientDemo.java
package com.infybank;
import java.util.Scanner;
import org.hibernate.HibernateException;
public class ClientDemo {
public static void main(String args[])
{
CustomerDAO custdao=new CustomerDAO();
try
{
System.out.println("CREATE");
System.out.println("Enter the customer details");
Scanner sc=new Scanner(System.in);
System.out.println("Enter the customer number");
int d=sc.nextInt();
System.out.println("Enter the customer name");
String name=sc.next();
Customer cust=new Customer(d,name);
custdao.addCustomer(cust);
System.out.println("One recort inserted");
}
catch(HibernateException ex)
{
System.out.println("Exception "+ex);
}
}}`
HibernateUtil.java
package com.infybank;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static
{
try
{
Configuration configuration =new Configuration().configure("/config/hibernate.cfg.xml");
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
}
catch(Throwable ex)
{
System.err.println("Initial sessionFactory creation failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}}
This is hibernate.cfg.xml file
<?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>
<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">Anak#1604</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.infybank.Customer"/>
</session-factory>
</hibernate-configuration>
Customer.java
package com.infybank;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="CUSTOMERID")
private int customerId;
#Column(name="CUSTOMERNAME")
private String customerName;
public Customer(int id,String name)
{
this.customerId=id;
this.customerName=name;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
CustomerDAO.java
package com.infybank;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CustomerDAO implements ICustomer{
#Override
public void addCustomer(Customer cust) {
// TODO Auto-generated method stub
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
session.save(cust);
tx.commit();
session.close();
}
}
Error
Exception org.hibernate.MappingException: Unknown entity: com.infybank.Customer
Facing the above error when tried to run the code
At least Hibernate entities should not have this kind of constructor with arguments:
public Customer(int id,String name)
{
this.customerId=id;
this.customerName=name;
}
See this answer for more information.
By default all entity classes should have a default constructor. This is required by Hibernate due to the fact that they are instantiated via reflection.
I believe you just need to add an empty constructor to your Customer class and it should be fine
public Customer(){}
Related
This question already has answers here:
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
(6 answers)
Closed 5 years ago.
I am creating a simple application using Hibernate JPA (annotations) and MySQL.I keep getting a:
WARN: HHH000183: no persistent classes found for query class: from
tn.ensi.cloudtrustproject.dao.entity.Country
when testing the Hibernate mapping.
I could not locate the problem so far. Please any help.
This is my hibernate.cfg.xml:
<!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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name=
"hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name=
"hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/TrustCloud</property>
<property name="hibernate.connection.pool_size">1</property>
<property name=
"hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider
</property>
<property name= "hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.Country" ></mapping>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.CloudUser"></mapping>
</session-factory>
</hibernate-configuration>
This is HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory= buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static Session session=null;
private static SessionFactory buildSessionFactory(){
try{
Configuration configuration= new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry=new
StandardServiceRegistryBuilder().
applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory (serviceRegistry);
}
catch (Throwable ex){
System.err.println("Failed to cerate SessionFactory object"+ ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session openSession(){
return sessionFactory.openSession();
}
public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public static void close(){
sessionFactory.close();
}
}
The class Test.java:
package tn.ensi.cloudtrustproject.util;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Test {
static Session session= HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("from tn.ensi.cloudtrustproject.dao.entity.Country
").list();
}
}
The entity class:
package tn.ensi.cloudtrustproject.dao.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="country")
public class Country implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
#Column(name="countryid")
private Integer countryId ;
#Column(name="countrydes")
private String countryDes;
public Country(Integer countryId, String countryDes) {
super();
this.countryId = countryId;
this.countryDes = countryDes;
}
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Integer getCountryId() {
return countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
public String getCountryDes() {
return countryDes;
}
public void setCountryDes(String countryDes) {
this.countryDes = countryDes;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "Country [countryId=" + countryId + ", countryDes=" + countryDes
+ "]";
}
}
The project:
project
The table is created:
Table country
you have mentioned configuration file exists in config/hibernate.cfg.xml. Please check whether it is existing in same location.
I'm trying to create a small project with hibernate, but i got that error "Type is not mapped [select o from Type o]", I added mapping in hibernate.cfg.xml but still error.
Type.java:
package com.formation.gestionprojet.doa.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Type")
public class Type implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String name;
private String description;
private String active;
public Type() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
}
hibernate.org.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 setting -->
<property name ="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/gestion_projet?createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name= "connection.password">root</property>
<!-- Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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>
<!-- Drope and re-create the database -->
<property name="hbm2ddl.auto">update</property>
<!-- mapping -->
<mapping class= "com.formation.gestionprojet.doa.entity.Type"/>
</session-factory>
</hibernate-configuration>
hibernateUtil.java:
package com.formation.gestionprojet.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
#SuppressWarnings("deprecation")
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
Configuration configuration = new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException ex)
{
System.err.println("Error creating Session: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static Session openSession()
{
return sessionFactory.openSession();
}
public static Session getCurrentSession()
{
return sessionFactory.getCurrentSession();
}
public static void close(){
if(sessionFactory!=null){
sessionFactory.close();
}
}
}
Test.Java
package com.formation.gestionprojet.utils;
import org.hibernate.Session;
public class Test {
static Session session = HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("select o from Type o").list();
}
}
solved ! the problem was the version of hibernate that I used so I change it, a change in HibernateUtil.
Iam trying to build a sample application with JAXRS/Hibernate.
I have sample data in my database,but i could not retrieve it.Please verify my code and let me know where Iam making error.
Entity class
package org.cricket.cricketstats.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Table(name="player_info")
#Entity
public class PlayerInfo {
#Id
#Column(name="player_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long playerId;
#Column(name="player_name")
private String playerName;
#Column(name="player_role")
private String playerRole;
#Column(name="player_batting_style")
private String playerBattingStyle;
#Column(name="player_bowling_style")
private String playerBowlingStyle;
#Column(name="player_image")
private String playerImage;
#Column(name="player_profile_desc")
private String playerProfile;
public PlayerInfo(){
}
public PlayerInfo(long playerId, String playerName, String playerRole, String playerBattingStyle,
String playerBowlingStyle, String playerImage, String playerProfile) {
super();
this.playerId = playerId;
this.playerName = playerName;
this.playerRole = playerRole;
this.playerBattingStyle = playerBattingStyle;
this.playerBowlingStyle = playerBowlingStyle;
this.playerImage = playerImage;
this.playerProfile = playerProfile;
}
public long getPlayerId() {
return playerId;
}
public void setPlayerId(long playerId) {
this.playerId = playerId;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerRole() {
return playerRole;
}
public void setPlayerRole(String playerRole) {
this.playerRole = playerRole;
}
public String getPlayerBattingStyle() {
return playerBattingStyle;
}
public void setPlayerBattingStyle(String playerBattingStyle) {
this.playerBattingStyle = playerBattingStyle;
}
public String getPlayerBowlingStyle() {
return playerBowlingStyle;
}
public void setPlayerBowlingStyle(String playerBowlingStyle) {
this.playerBowlingStyle = playerBowlingStyle;
}
public String getPlayerImage() {
return playerImage;
}
public void setPlayerImage(String playerImage) {
this.playerImage = playerImage;
}
public String getPlayerProfile() {
return playerProfile;
}
public void setPlayerProfile(String playerProfile) {
this.playerProfile = playerProfile;
}
}
Rest Resource
package org.cricket.cricketstats.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.cricket.cricketstats.data.PlayerInfoDAO;
import org.cricket.cricketstats.model.PlayerInfoBean;
#Path("players")
public class CricketResources {
PlayerInfoBean playerInfoBean= new PlayerInfoBean();
#GET
#Path("{playerId}")
#Produces(MediaType.APPLICATION_JSON)
public PlayerInfoBean getPlayerDetails(#PathParam("playerId") long id) {
PlayerInfoDAO dao= new PlayerInfoDAO();
dao.getPlayerInfo();
playerInfoBean.setPlayerId(id);
return playerInfoBean;
}
}
Config 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>
<!-- Connection settings -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/cricket</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">postgres</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Print executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- validate all database on startup -->
<property name="hibernate.hbm2ddl.auto">validate</property>
<!-- Annotated entity classes -->
<mapping class="org.cricket.cricketstats.data.PlayerInfo"/>
</session-factory>
</hibernate-configuration>
DAO class
package org.cricket.cricketstats.data;
import java.util.List;
import org.cricket.cricketstats.model.PlayerInfoBean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class PlayerInfoDAO {
public void getPlayerInfo(){
Configuration config=new Configuration().configure();
ServiceRegistry serviceRegistry= new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
//StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
// SessionFactory factory = config.buildSessionFactory(builder.build());
SessionFactory factory = config.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Transaction tx =session.beginTransaction();
List infoList=session.createQuery("FROM PlayerInfo").list();
tx.commit();
session.close();
System.out.println(infoList.get(0).getPlayerName());
}
}
**I have tried to give full path also in query **
The way is used by you to building a session factory is not correct for Hibernate 5. It can be used only for Hibernate 4.
Use this instead
SessionFactory factory = new Configuration().configure().buildSessionFactory();
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 am new to hibernate. i am following a tutorial and trying to execute a simple code but I am getting below error.
org.hibernate.MappingException: Unknown entity:
I am using annotations and configuration file also did exactly according the tutorials. I have googled but didn't get the correct answer
This is my code
package org.anne;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Demo {
public static void main(String[] args) {
Paper p = new Paper();
p.setPname("indu");
SessionFactory sf = HibernateUtil.getSessionFactory();
Session ses = sf.openSession();
Transaction tr = ses.beginTransaction();
ses.save(p);
tr.commit();
ses.close();
sf.close();
}
}
package org.anne;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
static SessionFactory sf;
public static SessionFactory getSessionFactory()
{
Configuration cf = new Configuration();
cf.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder srv = new StandardServiceRegistryBuilder();
StandardServiceRegistry sr = srv.applySettings(cf.getProperties()).build();
sf = cf.buildSessionFactory(sr);
return sf;
}
}
package org.anne;
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 = "PAPER")
public class Paper {
int pid;
String pname;
#Id
#Column(name = "PID")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
#Column(name = "PNAME")
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name = "connection.driver_class">com.mysql.jdbc.Driver</property>
<property name = "connection.url">jdbc:mysql://localhost:3306/test</property>
<property name = "connection.username">root</property>
<property name = "connection.password">abc123</property>
<property name = "hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name = "hibernate.show_sql">true</property>
<mapping class = "org.anne.Paper" />
</session-factory>
</hibernate-configuration>
If you boot Hibernate yourself, make sure to use the AnnotationConfiguration class instead of the Configuration class. Here is an example using the (legacy) HibernateUtil approach:
package hello;
import org.hibernate.*;
import org.hibernate.cfg.*;
import test.*;
import test.animals.Dog;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Log exception!
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession()
throws HibernateException {
return sessionFactory.openSession();
}
}
More here https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html#setup-configuration