node to traverse cannot be null SQL SELECT - java

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

Related

using hibernate and jpa with springboot

I have a spring boot project. I put in my resource folder hibernate.cfg.xml file.
this is my hibernate.cfg.xml 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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">***</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/exportbatch?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
I have a hibernateUtil class used to instantiate a hibernate session.
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory();
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
In my application controller I have an endpoint in which I am requesting my mysql database.
#RequestMapping("/getbuildinginfo/{buildingid}")
public void getbuildinginfo(String buildingid)
Session session = null;
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String query = "select * from exportbatch.exportbatch";
SQLQuery sqlQuery = session.createSQLQuery(query);
List<Object[]> rows = sqlQuery.list();
HibernateUtil.shutdown();
This works fine the first time I run the project, but if I call the endpoint a second time, I am getting this exception:
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
Could someone help me with this ? why it works the first time? Is it a spring boot context problem? if yes how could I resolve it ?

Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed

I want to run this very basic Hibernate code:
public static void main(String[] args) throws Exception
{
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
SystemUsers myContact = new SystemUsers(3);
SystemUsers yourContact = new SystemUsers(4);
SystemUsers yourContsact = new SystemUsers(5);
SystemUsers yourContssssact = new SystemUsers(6);
SystemUsers yourContssssasssct = new SystemUsers(7);
// Saving to the database
session.save(myContact);
session.save(yourContact);
session.save(yourContsact);
session.save(yourContssssact);
session.save(yourContssssasssct);
session.flush();
tr.commit();
List<SystemUsers> contactList = session.createQuery("from SYSTEM_USERS").list();
for (SystemUsers contact : contactList)
{
System.out.println("Id: " + contact.getId());
}
System.out.println("Successfully inserted");
sessFact.close();
}
config file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:/C:/sqlite/test.sqlite</property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.release_mode">auto</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.web.models.SystemUsers"/>
</session-factory>
</hibernate-configuration>
I get error:
Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:337)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:135)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:648)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
I use latest Hibernate version. Can you give me some advice how I can fix this issue?
Probably I need to initialize different factory?
i think the problem is in
session.flush();//this will flush all the data in the session so for commmiting there wont be any data.
tr.commit();
try this.
tr.commit();
session.flush();

I can't get get the SessionFactory in Hibernate 5.1.0. My code breaks in the line while getting the SessionFactory obj

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.

hibernate configuration exception

StackTrace:
Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at org.hibernate.tutorial.util.HibernateUtil.<clinit>(HibernateUtil.java:9)
at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:23)
at org.hibernate.tutorial.EventManager.main(EventManager.java:16)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 3 more
my hibernate config:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</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>
<!-- 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>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml" />
</session-factory>
</hibernate-configuration>
my code:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build());
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
public class EventManager {
public static void main(String[] args) {
EventManager mgr = new EventManager();
if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}
HibernateUtil.getSessionFactory().close();
}
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
}
}
Your sessionfactory property names are incorrect. They should be
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
Note the property name is hibernate.

hibernate.cfg.xml not found (eclipse)

I started using Hibernate today and tested a simple example but I'm getting the error: hibernate.cfg.xml not found.
I putted the hibernate.cfg.xml file in the src folder and here is its content:
<?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/test</property>
<property name="connection.username">test</property>
<property name="connection.password">test</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">update</property>
<mapping resource="com/mycompany/model/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And I putted the HibernateUtil.java file under util folder (src/util) and here is its content
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("hibernate.cgf.xml").buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
I also have the Jars added to the build path.
My class Test.java :
import ...
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductDao pd = new ProductDao();
try {
Product p = new Product("PC", 1000L);
pd.add(p);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The add method :
public void add(Product p) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.beginTransaction();
session.save(p);
tx.commit();
}
Thanks in advance
If using maven try putting it in
/src/main/resources
If using simple eclipse project (without maven), put it in project root directory (not in the src)
Also you misspelled the name of the file in the source
return new Configuration().configure("hibernate.cgf.xml").buildSessionFactory();
it must be
hibernate.cfg.xml
If its a Maven project just add cfg.xml file in /src/main/resources in eclips

Categories

Resources