Trying to learn Hibernate, i am trying to learn how to execute NamedQuries but evertime i am getting Exception in thread "main" org.hibernate.MappingException: Named query not known.Please help me out here
Error (only the message, not showing complete stack)
Exception in thread "main" org.hibernate.MappingException: Named query not known: hibernate_tut_emp.Employee.FindCountOfNames
at org.hibernate.internal.AbstractSessionImpl.getNamedQuery(AbstractSessionImpl.java:177)
at org.hibernate.internal.SessionImpl.getNamedQuery(SessionImpl.java:1372)
at hibernate_tut_emp.MyOps.main(MyOps.java:20)
Employee.java
package hibernate_tut_emp;
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.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#Table(name="Hib1")
#NamedQueries({
#NamedQuery(name="GetDetailsByName" , query="select * from hib1 h where h.name=:name"),
#NamedQuery(name="FindCountOfNames", query="select count(1) as cnt from hib1 h where h.name=:name")
})
public class Employee {
private int id;
private String name;
#Id
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String empName) {
this.name = empName;
}
}
MyOps.java
package hibernate_tut_emp;
import java.util.Scanner;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class MyOps {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a name : ");
String name = scnr.next();
SessionFactory ses = HibernateUtil.getSessionFactory();
Session session = ses.openSession();
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
query.setString("name", name);
int count = ((Integer)query.iterate().next()).intValue();
System.out.println("count : "+count);
}
}
employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate_tut_emp.Employee" table="hib1">
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="name" type="string" column="name" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?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>
<!-- 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">mayank</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>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="hibernate_tut_emp.Employee" />
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I googled out everything possible but i think i am overlooking some basic stuff.Any indication in right direction is appreciated! :)
One thing i considered is that if i have defined in class file NamedQueries, i do not need to mention it in xml file.Please correct me if i am wrong!
There are several issues here:
Your named queries should use entities not tables. If you want native queries you should use NamedNativeQuery instead.
You don't need to supply the entity name when fetching the query.
Change this:
Query query = session.getNamedQuery("hibernate_tut_emp.Employee.FindCountOfNames");
to:
Query query = session.getNamedQuery("FindCountOfNames");
Related
I am using Hibernate and PostgresSQL and am trying to create a table by .xml with no success.
I don't see an error when I start Main.class. Maybe I should use another version of Hibernate?
I'm using Gradle and added in dependencies for the latest versions of hibernate-core, hibernate-entitymanager, and hibernate-validator.
I have been watching video published in 2016: maybe there's a problem in it.
Hibernate cfg:
<?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="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.username">pavel</property>
<property name="connection.password">31228900</property>
<property name="connection.pool_size">10</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="planetofUsers.cfg.xml"/>
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateLesson.Planet" table="planet">
<id name="id" >
<generator class="native" />
</id>
<property name="age" column="age" type="int" />
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="last_name" type="string" />
</class>
</hibernate-mapping>
Java classes:
import lombok.Data;
import lombok.experimental.FieldDefaults;
import static lombok.AccessLevel.PRIVATE;
#Data
#FieldDefaults(level = PRIVATE)
public class Planet {
long id;
int age;
String firstName;
String
import lombok.experimental.FieldDefaults;
import org.hibernate.SessionFactory;
import static lombok.AccessLevel.PRIVATE;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
}
}
package hibernateLesson;
import lombok.experimental.FieldDefaults;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import static lombok.AccessLevel.PRIVATE;
#FieldDefaults(level = PRIVATE)
public class HibernateUtil {
static SessionFactory sessionFactory = null;
static {
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Use below setting :
hibernate.hbm2ddl.auto = create
This is my first Hibernate Application Program. I got this error when executing the main class.I Am trying to insert new record at the table student. Also it is good to say that hibernate doing the connection to the database without any problem !I keep getting this MappingException:
Hibernate: drop table if exists student
Hibernate: create table student (student_id integer not null auto_increment, First_Name varchar(255), Last_Name varchar(255), Age integer, primary key (student_id))
Dec 22, 2015 10:04:44 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.hibernate.internal.SessionImpl
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1146)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1358)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:116)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:206)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:683)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:675)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:671)
at biztime.Manager.main(Manager.java:23)
Does anyone have any ideas as I've looked at so many duplicates but the resolutions don't appear to work for me.This is my cfg.xml
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="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://localhost:3306/anwardb</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
<mapping resource="biztime/student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My student.java
package biztime;
public class student
{
private int student_id;
private String First_Name;
private String Last_Name;
private int Age;
public int getStudent_id()
{
return student_id;
}
public void setStudent_id(int student_id)
{
this.student_id = student_id;
}
public String getFirst_Name()
{
return First_Name;
}
public void setFirst_Name(String first_Name)
{
First_Name = first_Name;
}
public String getLast_Name()
{
return Last_Name;
}
public void setLast_Name(String last_Name)
{
Last_Name = last_Name;
}
public int getAge()
{
return Age;
}
public void setAge(int age)
{
Age = age;
}
}
student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="biztime">
<class name="student" table="student ">
<id name="student_id" column="student_id">
<generator class="native"/>
</id>
<property name="First_Name" >
<column name="First_Name"/>
</property>
<property name="Last_Name">
<column name="Last_Name"/>
</property>
<property name="Age">
<column name="Age"/>
</property>
</class>
</hibernate-mapping>
I call it using this main:
Manager.java
package biztime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Manager
{
public static void main(String[] args)
{
Configuration con=new Configuration();
con.configure();
SessionFactory sf=con.buildSessionFactory();
Session s1=sf.openSession();
student s=new student ();
s.setFirst_Name("hello");
s.setLast_Name("test");
s.setStudent_id(1);
s.setAge(20);
s1.beginTransaction();
s1.save(s1);
s1.getTransaction().commit();
s1.flush();
s1.close();
System.out.println("done");
}
}
You're attempting to save s1 which is a Session. Save s instead, which is a student (and capitalize your classnames).
I don't think you should set student_id, as it is an auto_increment field. Try removing this line: s.setStudent_id(1);
When I tried my first hibernate program and I got this error.
My program simply insert empID,first_name,second_name(table names) and using MySQL database.
Tried lot of solutions sill getting this error.
mapping file
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">anandhu</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update </property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="emp">
<id name="empID" column="empID" type="int">
<generator class="assigned"></generator>
</id>
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
</class>
</hibernate-mapping>
This is my persistence class
public class Employee {
private int empID;
private String firstName;
private String lastName;
public int getID(){
return empID;
}
public void setID(int empID){
this.empID = empID;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
}
This is my test class
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
public class EmployeeTest {
public static void main(String[] args) {
Configuration cf = new Configuration();
cf.configure("employee.cfg.xml");
SessionFactory factory = cf.buildSessionFactory();
Session session = factory.openSession();
Employee employee = new Employee();
employee.setID(30);
employee.setFirstName("raju");
employee.setLastName("ryan");
Transaction transaction = session.beginTransaction();
session.save(employee);
System.out.println("updated");
transaction.commit();
session.close();
factory.close();
}
}
stack trace
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: employee.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.anandhu.hibernateproject.EmployeeTest.main(EmployeeTest.java:16)
Caused by: org.dom4j.DocumentException: Error on line 3 of document :
The processing instruction target matching "[xX][mM][lL]" is not allowed.
Nested exception:
The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
The problem with this lines
<property name="firstName" column="first_name" type="string">
<property name="lastName" column="second_name" type="string">
Should be
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="second_name" type="string" />
It would be more simply to find a solution if you show all stacktrace.
You can find examples of working with a configuration and a session here.
Upated
I check this mapping and it works fine. Looks like you have incorrect symbols (may be spaces) in the xml header. May be this will be helpfull Error: The processing instruction target matching “[xX][mM][lL]” is not allowed.
I checked the numerous threads about this but no solutions are working. According to those threads, the mapping should work.
Exception in thread "main"
org.hibernate.hql.internal.ast.QuerySyntaxException: Product is not
mapped [from Product]
hibernate.cfg.xml
<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.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="api.test.model.Product" />
</session-factory>
</hibernate-configuration>
Product.java:
package api.test.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="products")
public class Product implements Serializable{
...
}
Dao:
public List<Product> getProduct(Integer id) {
List<Product> products = (List<Product>) openCurrentSessionwithTransaction()
.createQuery("from Product").setMaxResults(100).list();
return products;
}
This does not throw error but no results possible:
.createQuery("from " + Product.class.getName()).setMaxResults(100).list();
I also tried mapping the class in persistence.xml, doesn't work either:
<persistence-unit name="transactions-optional">
<class>api.test.model.Product</class>
Full stacktrace as requested
Thanks in advance.
Hi I am trying to use anotation to do named query. The line that caused Named query not known is:
HibernateUtil.openSession().getNamedQuery(
"getWorkById")
Here is all the code about my named query. Actually I also tried to do so in mapping files, but I also got error and don't know what error is because it just reported internal failure. Any help about how to fix the error? Also, what is a better practice to do named query? Thanks!
WorkModel:
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#NamedQueries({
#NamedQuery(name = "getWorkById", query = "from myday.work w where w.id = :id")
})
#Entity
#Table(name = "myday.work")
public class WorkModel {
private Long id;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
WorkModel hbm xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="model.WorkModel" table="myday.work">
<id name="id" type="java.lang.Long">
<column name="id" />
<generator class="increment" />
</id>
</class>
</hibernate-mapping>
hibernate cfg xml
<?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://XXX:3306</property>
// username, pwd setting...
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<mapping class="model.WorkModel"/>
<mapping resource="model/WorkModel.hbm.xml"/>
</session-factory>
</hibernate-configuration>