I'm trying to test the hibernate configuration of a project, but when I try to run the test it throws a MappinException saying that it does not known my entity, I checked the database and it is not creating the tables either, so my guess is that it is not reading the mapping files, but I checked that and the path is correct. And the package and class properties inside the mapping files is also correct (supposely).
Most of the questions I read are Annotation Focused, does anyone has an idea what's happening under the hood?
Thanks in advance
I have the following directory structure:
The hibernate.cfg.xml file it's like follows:
<hibernate-configuration>
<session-factory>
<!-- Hibernate Configuration -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<!-- Database Configuration -->
<property name="hibernate.connection.url">
jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
cetys
</property>
<!-- Class Mapping Files -->
<mapping resource="Hibernate.config/mapping/Book.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Classification.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Collection.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Loan.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/NonExistentRegistry.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Loan mapping file is:
<hibernate-mapping package="com.cetys.cetyslibraryinventory.Core.DomainModels">
<class name="Loan" table="loan">
<meta attribute="class-description">
This class contains the basic information for a Loan
</meta>
<id name="id" column="loan_id" type="int"></id>
<many-to-one name="bookId" class="Book" unique="true"
column="book_id" cascade="all"/>
</class>
</hibernate-mapping>
The model:
package com.cetys.cetyslibraryinventory.Core.DomainModels;
//imports ommited
public class Loan implements Catalogable {
private int id;
private int book_id;
protected Loan () {
}
public Loan ( int id, int book_id ) {
this.id = id;
this.book_id = book_id;
}
// Getters and Setters Ommited
}
And when I try to run the following:
public class Program {
public static void main ( String[] args ) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
Configuration configuration = new Configuration();
configuration.configure( "hibernate.cfg.xml" );
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties() ).build();
sessionFactory = configuration.
buildSessionFactory( serviceRegistry );
session = sessionFactory.openSession();
Loan ln = new Loan( 0, 0 );
tx = session.beginTransaction();
session.save( ln );
tx.commit();
} catch ( Exception e ) {
LOGGER.log( Level.SEVERE, e.getMessage(), e );
} finally {
if ( session != null ) {
session.close();
}
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
}
}
Exception Error:
SEVERE: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
org.hibernate.MappingException: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
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:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.cetys.cetyslibraryinventory.Program.main(Program.java:74)
Jun 08, 2016 10:04:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true]
Related
Full MCVE is at the bottom of this post.
I am trying to run a very basic Hibernate example as I work through a tutorial. However, I am receiving the following error: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:50)
at hibernateTutorial.util.HibernateUtil.getSessionFactory(HibernateUtil.java:30)
at hibernateTutorial.main.HibernateMain.main(HibernateMain.java:21)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:127)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:86)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:479)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:85)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:709)
at hibernateTutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:47)
... 2 more
Caused by: org.vibur.dbcp.ViburDBCPException: java.lang.NullPointerException
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:233)
at org.hibernate.vibur.internal.ViburDBCPConnectionProvider.configure(ViburDBCPConnectionProvider.java:57)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:107)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:246)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 15 more
Caused by: java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:460)
at java.util.Properties.setProperty(Properties.java:166)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:66)
at org.vibur.dbcp.pool.Connector$Builder$Driver.<init>(Connector.java:56)
at org.vibur.dbcp.pool.Connector$Builder.buildConnector(Connector.java:48)
at org.vibur.dbcp.ViburDBCPDataSource.doStart(ViburDBCPDataSource.java:248)
at org.vibur.dbcp.ViburDBCPDataSource.start(ViburDBCPDataSource.java:226)
... 24 more
My database is on a Microsoft SQL Server 2017 instance that uses Windows Authentication. I have added both the MSSQL JDBC (v6.4.0) updated IntelliJ with the -Djava.library.path VM option so that sqljdbc_auth.dll (required for Windows Authentication) is accessible.
From what I can tell in my research into this ambiguous error message, it could have many different causes, but ultimately boils down to just not being able to connect to the database somehow. Most of the other Q&A I've found seems to be specific to other databases or SQL Server that doesn't use Windows Authentication.
I have copied the JDBC URL directly from my datasource config in IntelliJ so I know that it is correct and works properly in the IDE.
What else is required to properly configure Hibernate to connect to SQL Server?
HibernateMain.java:
package hibernateTutorial.main;
import hibernateTutorial.model.Employee;
import hibernateTutorial.util.HibernateUtil;
import org.hibernate.Session;
import java.time.LocalDateTime;
public class HibernateMain {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("Nathan");
emp.setRole("CEO");
emp.setInsertTime(LocalDateTime.now());
// **********************************************************************************************
// Get Session
// **********************************************************************************************
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// **********************************************************************************************
// Start transaction
// **********************************************************************************************
session.beginTransaction();
// **********************************************************************************************
// Save the model object
// **********************************************************************************************
session.save(emp);
// **********************************************************************************************
// Commit the transaction
// **********************************************************************************************
session.getTransaction().commit();
System.out.println("Employee ID: " + emp.getId());
// **********************************************************************************************
// Terminate the session factory or the program won't end
// **********************************************************************************************
HibernateUtil.getSessionFactory().close();
}
}
HibernateUtil.java:
package hibernateTutorial.util;
import hibernateTutorial.model.Employee1;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import java.util.Properties;
public class HibernateUtil {
// **********************************************************************************************
// XML-based configuration
// **********************************************************************************************
private static SessionFactory sessionFactory;
// **********************************************************************************************
// Annotation-based configuration
// **********************************************************************************************
private static SessionFactory sessionAnnotationFactory;
// **********************************************************************************************
// Property-based configuration
// **********************************************************************************************
private static SessionFactory sessionJavaConfigFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) sessionFactory = buildSessionFactory();
return sessionFactory;
}
private static SessionFactory buildSessionFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creation failed. " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionAnnotationFactory() {
if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
return sessionAnnotationFactory;
}
private static SessionFactory buildSessionAnnotationFactory() {
try {
// **********************************************************************************************
// Create the SessionFactory from hibernate-annotation.cfg.xml
// **********************************************************************************************
Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable e) {
System.err.println("Initial SessionFactory creationg failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionJavaConfigFactory() {
if (sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
return sessionJavaConfigFactory;
}
private static SessionFactory buildSessionJavaConfigFactory() {
try {
Configuration configuration = new Configuration();
//Create Properties, can be read from property files too
Properties props = new Properties();
props.put("hibernate.connection.driver_class", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
props.put("hibernate.connection.url", "jdbc:sqlserver://FADBOKT2493V\\KRAFTLAKEODB:51678;database=Dev_RepAssistDB;integratedSecurity=true");
props.put("hibernate.current_session_context_class", "thread");
configuration.setProperties(props);
//we can set mapping file or class with annotation
//addClass(Employee1.class) will look for resource
// com/journaldev/hibernate/model/Employee1.hbm.xml (not good)
configuration.addAnnotatedClass(Employee1.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Java Config serviceRegistry created");
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
Employee.java:
package hibernateTutorial.model;
import java.time.LocalDateTime;
public class Employee {
private int id;
private String name;
private String role;
private LocalDateTime insertTime;
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;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public LocalDateTime getInsertTime() {
return insertTime;
}
public void setInsertTime(LocalDateTime insertTime) {
this.insertTime = insertTime;
}
}
Employee1.java:
package hibernateTutorial.model;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "tmp_employees",
uniqueConstraints =
{#UniqueConstraint(columnNames = {"id"})})
public class Employee1 {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
private int id;
#Column(name = "name", length = 20, nullable = true)
private String name;
#Column(name = "role", length = 20, nullable = true)
private String role;
#Column(name = "insert_time", nullable = true)
private LocalDateTime insertTime;
}
employee.hbm.xml:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernateTutorial.model.Employee" table="tmp_employees">
<id name="id" type="int">
<column name="id"/>
<generator class="increment"/>
</id>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="role" type="java.lang.String">
<column name="role"/>
</property>
<property name="insertTime" type="java.time.LocalDateTime">
<column name="insert_time"/>
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://servername:port;
database=test_db;integratedSecurity=true
</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping file, we can use Bean annotations too -->
<mapping resource="hibernateTutorial/employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate-annotation.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection properties - Driver, URL, user, password -->
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver:servername:port;database=test_db;integratedSecurity=true</property>
<!-- Connection Pool Size -->
<property name="hibernate.connection.pool_size">5</property>
<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Outputs the SQL queries, should be disabled in Production -->
<property name="hibernate.show_sql">true</property>
<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2012Dialect</property>
<!-- mapping with model class containing annotations -->
<mapping class="hibernateTutorial.model.Employee1"/>
</session-factory>
</hibernate-configuration>
I'm running my first hibernate project which saves user information such as id,name and address into mysql database
This is my error log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:109)
at org.hibernate.cfg.Configuration.add(Configuration.java:490)
at org.hibernate.cfg.Configuration.add(Configuration.java:486)
at org.hibernate.cfg.Configuration.add(Configuration.java:659)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:742)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2197)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2169)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2149)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2102)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2017)
at mypack.DataInsertion.insertInfo(DataInsertion.java:18)
at mypack.DataInsertion.main(DataInsertion.java:11)
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.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:78)
... 11 more
hibernate.cfg.xml (Configuration xml 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>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping xml)
<!-- Mapping File to POJO Class -->
<?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="mypack.DataProvider" table="user_info">
<id name="user_id" column="table_id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO class)
//POJO Class
package mypack;
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implentation java class)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
new DataInsertion().insertInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
}
Please advise me,,,
Thanks.
Try removing the comment line and blank line before the first tag in user.hbm.xml
Image
ERROR:
1) AdminModel.java - Model class.
2) HibernateUtil.java facilitates the Hibernate DB conn.
3) AdminDAO.java - u guyz know what these are...I'll save the pain to explain...and oh yes...m already through days of pain with this bug ...trynna debug...i've got deadlines to meet... if u guyz could help me it'd be a matter of great deal...
public class AdminModel {
private int adminID;
private String username;
private String password;
public int getAdminID() {
return adminID;
}
public void setAdminID(int adminID) {
this.adminID = adminID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HibernateUtil.java
public class HibernateUtil {
public static SessionFactory sessionFactory;
static {
try {
/* File f=new File("O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml");
sessionFactory =new Configuration().configure(f).buildSessionFactory();
*/
/****OR****/
String hibernatePropsFilePath = "O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
configuration.addResource("ekatabookstore.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
//throw new ExceptionInInitializerError(ex);
}
}
public static Session openSession() {
return HibernateUtil.sessionFactory.openSession();
//return sessionFactory.getCurrentSession();
}
}
AdminDAO.java
public AdminDAO(AdminModel adminUserObj) {
public void createAdmin() {
/*
* CRUD operation of HIBERNATE C-->Create SessionFactory Object is a
* heavy object and takes up huge resources, so it is better to create
* only one object and share it where needed.
*/
SessionFactory sessionFactoryObj = HibernateUtil.sessionFactory;
// System.out.println(sessionFactoryObj.getClass().getName());
Session session = sessionFactoryObj.openSession();
session.beginTransaction();// Transaction Started
session.save(adminObj);// SAVED
session.getTransaction().commit();// Transaction Ended
System.out.println("!!!SUCCESSFUL CREATE!!!");
session.close();// CLOSE session resource of Hibernate
Notification.notificationMsg = "ADMIN CREATE - SUCCESSFUL!";
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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://localhost:3306/ekatabookstoreDB</property>
<property name="connection.username">xyz</property>
<property name="connection.password">xyz</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.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> -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="ekatabookstore.hbm.xml" />
</session-factory>
</hibernate-configuration>
hbn.properties
hiberNateCfgFileName=hibernate.cfg.xml
ekatabookstore.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="com.ekatabookstore.layer.service.model.AdminModel" table="admin">
<id name="adminID" type="integer" column="id_admin">
<generator class="assigned" />
</id>
<property name="username" type="string" column="username" not-null="true" />
<property name="password" type="string" column="password" not-null="true" />
</class>
</hibernate-mapping>
If you are using spring then, Add autowire on sessionfactory or get it from application context. You can use following code
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
#Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
You can use this class anywhere in your code like
ApplicationContextProvider.getApplicationContext().getBean("sessionFactory");
Please try the following code for creating sessionfactory
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}
Hope this helps.
I have a problem with a query in HQL also my SQL base has some databases , so need to put together a query that take this table at the bottom, my sql base always starts in database 'database' and I must refer to the database webproduction then so I wrote my query :
#Entity
#Table(name="File")
#NamedQueries(
{
#NamedQuery(name="file.allList",
query = "use webproduction select * from File")
}
)
My Config:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://10.11.1.05</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- <mapping class="entity.Sell" /> -->
<mapping class="entity.File" />
</session-factory>
</hibernate-configuration>
My Class hibernate:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure(
"config/sql_hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My method:
public List<File> getFile() throws Exception{
session = HibernateUtil.getSessionFactory().openSession();
query = session.getNamedQuery("file.allList");
List<File> list1 = query.list();
session.close();
return list1;
}
For SQL server you would remove the 'use webproduction' from your named query and use:
jdbc:sqlserver://10.11.1.05;DatabaseName=webproduction
as your hibernate.connection.url
see http://www.java2s.com/Tutorial/Java/0340__Database/AListofJDBCDriversconnectionstringdrivername.htm
I am trying to learn hibernate framework with making a simple program that push a class Cliente into a table on postgres, The error that returns is as follow:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: the relation "clienti_id_seq" does not exist
This is my database by PGAdmin (sorry for imgur i can't upload picture directly) http://i.imgur.com/Fz9o1fR.png?1
This is the class Cliente
public class Cliente {
private long clienteId;
private String clienteNome;
private String clienteCognome;
private String clienteTelefono;
private String clienteMail;
private String clientePermesso;
private long clienteCommessa;
public long getClienteId() {
return clienteId;
}
public void setClienteId(long clienteId) {
this.clienteId = clienteId;
}
public String getClienteNome() {
return clienteNome;
}
public void setClienteNome(String clienteNome) {
this.clienteNome = clienteNome;
}
public String getClienteCognome() {
return clienteCognome;
}
public void setClienteCognome(String clienteCognome) {
this.clienteCognome = clienteCognome;
}
public String getClienteTelefono() {
return clienteTelefono;
}
public void setClienteTelefono(String clienteTelefono) {
this.clienteTelefono = clienteTelefono;
}
public String getClienteMail() {
return clienteMail;
}
public void setClienteMail(String clienteMail) {
this.clienteMail = clienteMail;
}
public String getClientePermesso() {
return clientePermesso;
}
public void setClientePermesso(String clientePermesso) {
this.clientePermesso = clientePermesso;
}
public long getClienteCommessa() {
return clienteCommessa;
}
public void setClienteCommessa(long clienteNome) {
this.clienteCommessa = clienteCommessa;
}
}
This is my mapping file
<hibernate-mapping>
<class name="beans.Cliente" table="Clienti">
<id name="clienteId" type="integer" column="id" >
<generator class="sequence">
<param name="sequence">CLIENTI_ID_seq</param>
</generator>
</id>
<property name="clienteNome" column="nome" type="string">
</property>
<property name="clienteCognome" column="cognome" type="string">
</property>
<property name="clienteTelefono" column="telefono" type="string">
</property>
<property name="clienteMail" column="mail" type="string">
</property>
<property name="clientePermesso" column="permesso" type="string">
</property>
<property name="clienteCommessa" column="commessa" type="string">
</property>
</class>
</hibernate-mapping>
This is the hibernate cfg.xml file, the information about url pass and user are correct
<?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.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql:postgres</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Georilievi</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">Fabio1990</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="Clienti.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is the main file, here i create an istance of Cliente, and try to push in the postgres database
package main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import beans.Cliente;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction
session.getTransaction().begin();
Cliente cliente = new Cliente();
cliente.setClienteNome("Fabio");
cliente.setClienteCognome("Tramontana");
cliente.setClienteTelefono("3343052346");
cliente.setClienteMail("info.tramontanafabio#gmail.com");
cliente.setClientePermesso("admin");
cliente.setClienteCommessa(0);
// Save*/
session.save(cliente);
// Commit, calling of commit will cause save an instance of employee
session.getTransaction().commit();
}
}
thanks all of you for helping me, i don't understand the error, i think it is in the declaration of the generator.
Please try changing the generator class from sequence to identity and see. I guess the issue is the auto generation of IDs.
See these links:
http://www.roseindia.net/hibernate/hibernateidgeneratorelement.shtml
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-property