NamedQueries problem with Hibernate - java

I used NanedQueries (as follows) in my JPA project Eclipselink as persistence provider:
#Entity
#Table(name = "login")
#NamedQueries({
#NamedQuery(name = "Login.random", query = "SELECT l FROM Login l WHERE l.pk = :randomPk"),
#NamedQuery(name = "Login.max", query = "SELECT MAX(l.pk) FROM Login l")
})
But after I change Hibernate as my persistence provider, I get the following error:
java.lang.IllegalArgumentException: org.hibernate.QueryException: unexpected char: '{' [SELECT...
I use Hibernate 3.2.5 (MySQL dialect)

Not having your exact configuration makes this difficult. But I didn't have an issue with hibernate 3.2.5.GA
I created the following Login Domain object:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name = "login")
#NamedQueries({
#NamedQuery(name = "Login.random", query = "select l FROM Login l WHERE l.pk = :randomPk"),
#NamedQuery(name = "Login.max", query = "select max(l.pk) from Login l")
})
public class Login implements Serializable {
private Long pk;
private String username;
public Login() {}
public Login(Long pk, String username) {
this.pk = pk;
this.username = username;
}
#Id
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import sky.sns.domain.Login;
import static org.junit.Assert.assertEquals;
public class AnnotationTest {
private static SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
#BeforeClass
public static void initialise() {
sessionFactory = new AnnotationConfiguration().configure("/hibernate-annotation.cfg.xml").buildSessionFactory();
}
#Before
public void setUp() {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
}
#After
public void tearDown() {
transaction.rollback();
}
#Test
public void createUser() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.get(Login.class, 1L);
assertEquals(login.getPk(), persistedLogin.getPk());
}
#Test
public void obtainUserByIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.getNamedQuery("Login.random").setLong("randomPk", 1L).uniqueResult();
assertEquals(login.getPk(), persistedLogin.getPk());
}
#Test
public void obtainMaxUserIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Long maxId = (Long)session.getNamedQuery("Login.max").uniqueResult();
assertEquals(login.getPk(), maxId);
}
}
My hibernate-annotation.hbm.xml file is as follows:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.jboss.org/dtd/hibernate/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/hibernate_owner</property>
<property name="hibernate.connection.username">hibernate_owner</property>
<property name="hibernate.connection.password">hibernate</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable 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>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.use_sql_comments">false</property>
<mapping class="sky.sns.domain.Login" />
</session-factory>
</hibernate-configuration>
Can you try this in your environment and let me know how you get on

Related

Hibernate exception class is not mapped

Hey i am new to hibernate and java and im getting this exception i tried multiple solutions i found on google and nothing seems to work. Would appreciate any help. I am trying to return number of rows from table in database.
I am using mapping in xml file and im using addAnnotatedClass yet it is still throwing exception.
Here is my code:
Main.java
package springfoxdemo.java.swagger;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Main {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static void main(String args[]) {
Session session = null;
try
{
try
{
Configuration cfg= new Configuration().addAnnotatedClass(Polica.class);
cfg.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
catch(Throwable th)
{
System.err.println("Failed to create sessionFactory object."
+ th);
throw new ExceptionInInitializerError(th);
}
session = sessionFactory.openSession();
Query query = session.createQuery("select count(p) from Polica p");
Iterator count = query.iterate();
System.out.println("No. of rows : "+ count.next());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
session.close();
}
}
}
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>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.password">PASS</property>
<property name="hibernate.connection.url">DBCONNECTION</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="springfoxdemo.java.swagger.Polica"/>
</session-factory>
</hibernate-configuration>
Polica.java
package springfoxdemo.java.swagger;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
public class Polica {
#Id
#GeneratedValue
#Column(name="id")
private int id;
#Column(name="ime_pol")
private String ime_pol;
public Polica() {
super();
}
public Polica(int id, String ime_pol) {
this.id = id;
this.ime_pol = ime_pol;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIme_pol() {
return ime_pol;
}
public void setIme_pol(String ime_pol) {
this.ime_pol = ime_pol;
}
}
Exception:
Polica is not mapped [select count(p) from Polica p]

Enity is not mapped - hibernate

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();
}
}
First things first, Type is part of the JPA/Hibernate API. So consider renaming it, e.g. MyType or something similar.
Secondly, select is not mandatory in HQL. So you can simply et everything with only FROM clause.
Thirdly, try using fully qualified name of the class in the query.
"FROM com.formation.gestionprojet.doa.entity.MyType"

HSQLDB with Hibernate producing empty results

I try to save\get some data to\from my DB but with no result.
Server log: Hibernate: select user0_.ID as ID1_0_, user0_.LOGIN as LOGIN2_0_, user0_.PASSWORD as PASSWORD3_0_ from USER user0_
OR
Hibernate: drop table USER if exists
Hibernate: create table USER (ID integer generated by default as identity (start with 1), LOGIN varchar(255), PASSWORD varchar(255), primary key (ID))
Hibernate: insert into USER (ID, LOGIN, PASSWORD) values (default, ?, ?)
I've no any idea what's the problem.
I'm using Jetty, in-memory DB
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.archive.autodetection">class,hbm</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.username">SA</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:hsqldb:mem:dvd</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="secure.entity.User"></mapping>
</session-factory>
</hibernate-configuration>
User
package secure.entity;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "USER")
public class User implements Serializable {
#Id
#Column(name = "ID")
#GeneratedValue
private Integer id;
#Column(name = "LOGIN")
private String login;
#Column(name = "PASSWORD")
private String password;
public User() {
}
public long getId(){ return this.id; }
public void setId(int id){ this.id = id; }
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HibernateUtil
package secure.config;
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 SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
if (sessionFactory == null)
{
Configuration configuration = new Configuration().configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
UserService
package secure.service;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
import secure.config.HibernateUtil;
import secure.entity.User;
import java.util.List;
#Service
public class UserServiceImpl implements UserService {
#Override
public User getByLogin(String login) {
User usr = new User();
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//String hql = "from User where login = :login";
Query query = session.createQuery("FROM User");//.setParameter("login", login);
List usrList = query.list();
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return usr;
}
}

Needed to restart Eclipse to do Hibernate changes

I'm learning Hibernates and while practising I came across this strange problem. Sometimes, when I do my changes and run the program, all of a sudden my Eclipse console gets stuck showing the last line as Hibernate: drop table UserDetails. To get the program running I need to restart my Eclipse program.
Below is my code.
UserDetails.java
package org.hibernates.dto;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
public class UserDetails {
#Id
#Column(name = "User_ID")
private int userId;
#Column(name = "User_Name")
private String userName;
#Temporal(TemporalType.TIME)
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
#Lob
private String address;
private String desription;
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;
}
}
HibernatesTest.java
package org.hibernates.dto;
import java.util.Date;
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 HibernatesTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("User 1");
user.setDate(new Date());
user.setAddress("User Address");
user.setDesription("User Desription");
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = (StandardServiceRegistryBuilder) new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = builder.build();
SessionFactory factory = configuration.buildSessionFactory(serviceRegistry);
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
}
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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://U0138039-TPD-A\\SQLEXPRESS:1433;DatabaseName=HibernatesDataBase</property>
<property name="connection.username">sa</property>
<property name="connection.password">T!ger123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.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">create</property>
<!-- Names the annotated entity class -->
<mapping class="org.hibernates.dto.UserDetails" />
</session-factory>
</hibernate-configuration>
How can I fix this?
You need to close the session factory
factory.close()

defining collections in hibernate through annotations

I am new to the concepts of hibernate and annotations .Currently I am making program on collections in hibernate.
Actually following is code of my program
person.class
package com;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "PesonSubjects")
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#ElementCollection
private Set<Subjects> subjectList = new HashSet<Subjects>();
public Set<Subjects> getSubjectList() {
return subjectList;
}
public void setSubjectList(Set<Subjects> subjectList) {
this.subjectList = subjectList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MAIN class
package com;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class Personmain {
/**
* #param args
*/
public static void main(String[] args) {
SessionFactory sessionfactory = new AnnotationConfiguration()
.configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
Person person = new Person();
person.setName("vikram");
Subjects subjects1 = new Subjects();
subjects1.setAuthor("xxxxxxxx");
subjects1.setISBN(10111);
subjects1.setName("mein kampf");
subjects1.setPublicationHouse("tmh");
person.getSubjectList().add(subjects1);
Subjects subjects2 = new Subjects();
subjects2.setAuthor("bbbbb");
subjects2.setISBN(10112);
subjects2.setName("harry porter");
subjects2.setPublicationHouse("William");
person.getSubjectList().add(subjects2);
session.save(person);
session.getTransaction().commit();
session.close();
}
}
subjects class
package com;
import javax.persistence.Embeddable;
#Embeddable
public class Subjects {
private int ISBN;
private String name;
private String Author;
private String publicationHouse;
public int getISBN() {
return ISBN;
}
public void setISBN(int iSBN) {
ISBN = iSBN;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
public String getPublicationHouse() {
return publicationHouse;
}
public void setPublicationHouse(String publicationHouse) {
this.publicationHouse = publicationHouse;
}
}
my configuration 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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/AnnotationCollections</property>
<property name="connection.username">root</property>
<property name="connection.password">cccccccc</property>
<property name="hbm2ddl.auto">create</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 class="com.Person" />
</session-factory>
</hibernate-configuration>
Now through the program I want a collection of subjects to enter into a table (I am not annotating subjectList as i want it to be collection and not in tabular format)
ie it should store values in collection fomat
However I am getting the following error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Set, for columns: [org.hibernate.mapping.Column(subjectList)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:410)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1099)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1284)
at com.Personmain.main(Personmain.java:14)
Is there something else to define ??
Thanks
For security's sake, keep both classes mapped:
<mapping class="com.Person" />
<mapping class="com.Subjects" />
Besides that, your code seems to be inferring the wrong access type.
Try adding:
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
to Person. Like:
#Entity
#Table(name = "PesonSubjects")
#javax.persistence.Access(javax.persistence.AccessType.FIELD)
public class Person {
If that does not work, try adding to both Person and Subjects.

Categories