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
Related
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(){}
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 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 am new to Java Hibernate. I setup a dynamic web project in eclipse and trying to insert a row in mysql db. I am getting the following error when I run my code on server.
java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ClassLoaderDelegate
org.hibernate.boot.internal.MetadataBuilderImpl.(MetadataBuilderImpl.java:127)
org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:135)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:655)
My hibernate.cfg.xml
<session-factory>
<!-- Database connection settings -->
<property name='connection.driver_class'>com.mysql.jdbc.Driver</property>
<property name='connection.url'>jdbc:mysql://localhost:3306/bornscientific</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>
<!-- Echo all executed SQL to stdout -->
<property name='show_sql'>true</property>
<!-- Mapping files -->
<mapping class="com.bornscientific.persistence.beans.Tags"/>
</session-factory>
My entity class
package com.bornscientific.persistence.beans;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "TAGS")
public class Tags implements Serializable
{
private Long id;
private String name;
public Tags()
{
}
#Id
#SequenceGenerator(name="seq1",sequenceName="HIB_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq1")
#Column(name = "TAG_ID", unique = true, nullable = false)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
#Column(name = "NAME", unique = true, length = 100, nullable = false)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
And my main method is
public static void test() throws Exception
{
try
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.getTransaction();
tx.begin();
Tags tags = new Tags();
tags.setName("TAG_1");
session.save(tags);
tx.commit();
System.out.println("Saved successfully...");
}
catch(Exception e)
{
//System.out.println(e)
e.printStackTrace();
}
}
HibernateUtil.java
package com.bornscientific.persistence;
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 = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw ex;
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
And this is the library referenced.
Please help me fix this issue. I have searched through google and could not find a solution.
I am using Java,Maven,Hibernate 3/JPA ,Eclipse to implement a PUT method for populating a Mysql db.
Here is my POJO
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "Person", catalog = "mydb", uniqueConstraints = {
#UniqueConstraint(columnNames = "Person"),})
public class Person implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String Name;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", unique = true, nullable = false, length = 30)
public String getName() {
return flowName;
}
public void setName(String Name) {
this.Name = Name;
}
}
Here is my annotations class.
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.google.gson.Gson;
import com.tracker.domain.Flow;
import com.tracker.persistence.HibernateUtil;
public class PersonService {
private Logger LOG = Logger.getLogger(TrackerService.class);
String JsonString = "{\"name\":\"John Doe\"}";
Gson gson = new Gson();
Person person = gson.fromJson(JsonString,Person.class);
#PUT
#Path("")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void processandSaveJson(Person person) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
String Name = Person.getName();
person.setName(Name);
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
}
}
Here is my Hibernate.Util.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
Here is my SessionFactory Context Listener class
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.Logger;
import org.hibernate.Session;
#WebListener
public class SessionFactoryListener implements ServletContextListener {
private Logger LOG = Logger.getLogger(SessionFactoryListener.class);
#Override
public void contextInitialized(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextInitialized()---\n");
}
Session session = HibernateUtil.getSessionFactory().openSession();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (LOG.isInfoEnabled()) {
LOG.info("\n\tInside contextDestroyed()\n");
}
HibernateUtil.shutdown();
}
}
When I try to run this using Tomcat Server, i get the following error.
type Status report
message Method Not Allowed
description The specified HTTP method is not allowed for the requested resource.
I am very new to this. Kindly let me know what I am doing wrong. I trying to insert a
record into a mysql db using the above values. Kindly help me out.
Thanks,
Jack
as mentioned in the comments, you should supply your calling code along with the rest. but since you already mentioned that you're using a browser to make the request, it should be mentioned that most/no browsers support 'put' without using javadcript. what you are doing looks like a simple 'get'.
so the solution is to either use javascript in your form submission, or discard REST and have Urls that reflect the method (eg. /person/new/ and /person/{personId}