Dropwizard-Hibernate - IllegalArgumentException: No query defined for that name - java

Apologies for asking this when other people have asked before, but the other solutions appear to use #ComponentScan which is for Spring, and I am using dropwizard, so that wont work for me.
This is my (pretty simple) DTO class.
package apidto.entity.organization;
import lombok.Data;
import javax.persistence.*;
#Entity
#Table(name = "organization")
#NamedQueries({#NamedQuery( name =
"apidto.entity.organization.Organization.findAll",
query = "SELECT o from Organization o")})
public #Data class Organization {
#Id
private long id;
#Column(name = "name")
private String name;
}
and I have the following DAO class...
import apidto.entity.organization.Organization;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import java.util.List;
public class OrganizationDAO extends AbstractDAO<Organization> {
public OrganizationDAO(SessionFactory sessionFactory)
{
super(sessionFactory);
}
public List<Organization> findAll()
{
return list(namedQuery("apidto.entity.organization.Organization.findAll"));
}
}

You should use ScanningHibernateBundle in the Application class. ScanningHibernateBundle will scan apidto.entitypackage and all nested packages and add all classes with #Entity annotation to the Hibernate SessionFactory.
class SomeApp extends Application<SomeConfiguration> {
#Override
public void initialize(Bootstrap<SomeConfiguration> bootstrap) {
HibernateBundle<SomeConfiguration> hibernate = new ScanningHibernateBundle<SomeConfiguration>(
"apidto.entity") {
#Override
public PooledDataSourceFactory getDataSourceFactory(SomeConfiguration configuration) {
return configuration.getDataSourceFactory();
}
};
bootstrap.addBundle(hibernate);
}
}

I had the same problem using Dropwizard and Hibernate. I had a User entity class like this:
#Entity
#Table(name = "users")
#NamedQueries({
#NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findAll",
query = "SELECT u FROM User u"),
#NamedQuery(name = "com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword",
query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String username;
private String password;
/*private List<Bookmark> bookmarks = new ArrayList<>();*/
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
...
And then I had my DAO class as:
public class UserDAO extends AbstractDAO<User> {
UserDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
List findAll() {
return list(namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findAll"));
}
public Optional<User> findByUsernamePassword(String username, String password) {
return Optional.ofNullable(uniqueResult(
namedQuery("com.majidkhorsandi.dropbookmarks.core.User.findByUsernamePassword")
.setParameter("username", username)
.setParameter("password", password)
));
}
}
Then here is how my hibernate.cfg.xml looked:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1</property>
<property name="connection.username">sa</property><!--./target/example-->
<property name="connection.password">sa</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Enable Hibernate's current sessions tracking by thread of execution -->
<property name="current_session_context_class">managed</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>
<mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>
</session-factory>
</hibernate-configuration>
I thought that the mapping tag in the hibernate.cfg.xml should be enough to do the mapping of User:
<mapping class="com.majidkhorsandi.dropbookmarks.core.User"/>
but Apparently, it was not. So What I had to do was to add the following extra line to the class in which I am building the SessionFactory using the hibernate configuration (in my case HibernateUtil):
configuration.addAnnotatedClass(User.class);
So eventually here is how my HibernateUtil looked like after the fix:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(User.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Related

Testing Hibernate mapping : no persistent classes found for query classes [duplicate]

This question already has answers here:
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
(6 answers)
Closed 5 years ago.
I am creating a simple application using Hibernate JPA (annotations) and MySQL.I keep getting a:
WARN: HHH000183: no persistent classes found for query class: from
tn.ensi.cloudtrustproject.dao.entity.Country
when testing the Hibernate mapping.
I could not locate the problem so far. Please any help.
This is my hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name=
"hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name=
"hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/TrustCloud</property>
<property name="hibernate.connection.pool_size">1</property>
<property name=
"hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider
</property>
<property name= "hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.Country" ></mapping>
<mapping class="tn.ensi.cloudtrustproject.dao.entity.CloudUser"></mapping>
</session-factory>
</hibernate-configuration>
This is HibernateUtil:
public class HibernateUtil {
private static SessionFactory sessionFactory= buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static Session session=null;
private static SessionFactory buildSessionFactory(){
try{
Configuration configuration= new Configuration();
configuration.configure("config/hibernate.cfg.xml");
serviceRegistry=new
StandardServiceRegistryBuilder().
applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory (serviceRegistry);
}
catch (Throwable ex){
System.err.println("Failed to cerate SessionFactory object"+ ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session openSession(){
return sessionFactory.openSession();
}
public static Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public static void close(){
sessionFactory.close();
}
}
The class Test.java:
package tn.ensi.cloudtrustproject.util;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class Test {
static Session session= HibernateUtil.openSession();
public static void main(String[] args) {
session.createQuery("from tn.ensi.cloudtrustproject.dao.entity.Country
").list();
}
}
The entity class:
package tn.ensi.cloudtrustproject.dao.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#Table(name="country")
public class Country implements Serializable{
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
#Column(name="countryid")
private Integer countryId ;
#Column(name="countrydes")
private String countryDes;
public Country(Integer countryId, String countryDes) {
super();
this.countryId = countryId;
this.countryDes = countryDes;
}
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Integer getCountryId() {
return countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
public String getCountryDes() {
return countryDes;
}
public void setCountryDes(String countryDes) {
this.countryDes = countryDes;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
#Override
public String toString() {
return "Country [countryId=" + countryId + ", countryDes=" + countryDes
+ "]";
}
}
The project:
project
The table is created:
Table country
you have mentioned configuration file exists in config/hibernate.cfg.xml. Please check whether it is existing in same location.

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 InvocationTargetException by saving

I am trying to add Hibernate 5 as ORM for a backend to connect with a MySQL-database. I read many examples and tutorials but I always get an InvocationTargetException.
Here are the relevant code. Hope someone can help me.
hibernate.cfg.xml
<?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.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/cooking</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="de.fani.cooking.object.User"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
package de.fani.cooking.hibernate;
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;
private static SessionFactory buildSessionFactory()
{
try
{
// Create session factory from cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Throwable ex)
{
System.err.println("Initial session factory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
if (sessionFactory == null)
{
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
User.java
package de.fani.cooking.object;
import javax.persistence.*;
#Entity (name = "User")
#Table(name="User", uniqueConstraints={#UniqueConstraint(columnNames = {"id"})})
public class User
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column (name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column (name = "username", nullable = false, length = 30)
private String username;
#Column (name = "password", nullable = false, length = 256)
private String password;
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public User()
{
}
}
SQL
CREATE TABLE `User` (
`id` int(11) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
UserResource.java
package de.fani.cooking.resource;
import de.fani.cooking.hibernate.HibernateUtil;
import de.fani.cooking.object.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/user")
public class UserResource
{
#POST
#Path("register")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response register(User _user)
{
User test = new User();
test.setId(24);
test.setUsername("tester");
test.setPassword("secret");
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(test);
session.getTransaction().commit();
session.flush();
return Response.status(Response.Status.OK).entity(_user).build();
}
}
Exception at session.save(test);:
SCHWERWIEGEND: Servlet.service() for servlet [ApplicationConfig] in context with path [] threw exception [org.hibernate.MappingException: Unknown entity: de.fani.cooking.object.User] with root cause
org.hibernate.MappingException: Unknown entity: de.fani.cooking.object.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1462)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:338)
at com.sun.proxy.$Proxy58.save(Unknown Source)
Thanks a lot!
Ok, I found the answer by myself. The problem was the way I initialized the configuration, if I understand it correctly.
I changed it to:
private static SessionFactory buildSessionFactory()
{
try
{
// Create session factory from cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml")
.build();
Metadata Meta = new MetadataSources(serviceRegistry)
.addAnnotatedClass(User.class)
.addAnnotatedClassName("de.fani.cooking.model.User")
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
SessionFactory sessionFactory = Meta.getSessionFactoryBuilder()
.build();
return sessionFactory;
}
catch (Throwable ex)
{
System.err.println("Initial session factory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
And now it works! :-)

Table is not mapped - HIBERNATE

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.

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