Table is not mapped - HIBERNATE - java

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.

Related

org.hibernate.QueryException: Unable to resolve path, unexpected token [trying to use left join]

I've created 2 entity classes:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "fr")
public class FR {
#Id
#Column(name = "id")
private String id;
#Column(name = "pid")
private String pId;
#Column(name = "pname")
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
and
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ar")
public class AR {
#Id
#Column(name = "id")
private String id;
#Column(name = "value1")
private String value1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
}
and I'm trying to join these tables to fetch the record.
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123");
but getting an exception:
org.hibernate.QueryException: Unable to resolve path [FR.id], unexpected token [FR] [from entities.FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123]
and when I'm removing FR from the query
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where id=123 or pId=123");
getting another exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from entities.FR left join AR on FR.pId = AR.id where id=123 or pId=123]
I'm in a learning stage of Hibernate and don't know what to do now.
If you've any other info regarding Left Join or the other Joins then please share that too.
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.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/examples?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root#123</property>
<property name="hibernate.show_sql">true</property>
<mapping class="entities.FR"/>
<mapping class="entities.AR"/>
</session-factory>
</hibernate-configuration>
Main Class
package hibernate.joins;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateJoins {
public static void main(String[] args) {
SessionFactory sessionFactory = getSessionFactory();
Session session = sessionFactory.openSession();
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id and ( FR.id=123 or FR.pId=123 )");
List list = qry.list();
list.forEach(System.out::println);
session.close();
sessionFactory.close();
}
public static SessionFactory getSessionFactory () {
SessionFactory sessionFactory = new Configuration().configure("configurations/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
}
Since you are using ON clause in your query, therefore, you can not to use where clause separately. Just keep on adding the condition using AND or OR clause(whichever is applicable)

Hibernate HHH000183: no persistent classes found for query class

I have a question about my hibernate mapping, I am creating a project with Spring and hibernate, I am facing a issue that I can solve it so far and I couldn't find someone able to help me so far, so I mapped the database and did everything as expected but I am receiving this message:
HHH000183: no persistent classes found for query class: FROM com.inbox.model.Estado
My hibernate.cfg.xml is like this
<?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="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://inboxmysqldb.c4lcntgo83fr.us-west-2.rds.amazonaws.com</property>
<property name="hibernate.connection.username">inboxuser</property>
<property name="hibernate.connection.password">xxxxxx</property>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> -->
<property name="hibernate.show_sql">false</property>
<!-- <property name="hibernate.hbm2ddl.auto">true</property>-->
<property name="hibernate.connection.pool_size">10</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Mapping files -->
<!-- <mapping class="com.inbox.model.Box"/> -->
<mapping class="com.inbox.model.Estado"/>
</session-factory>
</hibernate-configuration>
My class is mapped like this:
package com.inbox.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity(name="com.inbox.model.Estado")
#Table(name = "estado",
uniqueConstraints={#UniqueConstraint(columnNames={"id"})})
public class Estado implements IdentifierInterface, Serializable{
/**
*
*/
private static final long serialVersionUID = 3625863483844458267L;
#Id
#GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
#Column(name="id", nullable=false, unique=true, length=11)
private Integer id;
#Column(name="nome", length=20, nullable=true)
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() {
return getSessionFactory().openSession();
}
}
As requested follow the query
public T findById(int id) {
Session session = HibernateUtil.getSession();
session.beginTransaction();
try {
Query byIdQuery = session.createQuery("FROM " + entityClassName + " as c WHERE c.id = :id");
byIdQuery.setParameter("id", id);
return (T) byIdQuery.uniqueResult();
} catch (Exception e) {
throw new InboxException(e);
} finally {
session.close();
}
}
I ran out of ideas to try fix.
Thanks in advance

Hibernate Not retrieving the data

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();

org.hibernate.MappingException: Unknown entity - What is the root cause?

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

NoClassDefFoundError - ClassLoaderDelegate - Hibernate

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.

Categories

Resources