How to load hibernate.cfg.xml from different location - java

I am creating a jar using hibernate. I have encountered a situation where I need to change a setting (url) often, so I would like to load the hibernate.cfg.xml like this
SessionFactory sessionFactory = new Configuration()
.configure("D:\\fax\\hibernate.cfg.xml")
.buildSessionFactory();
But then running the project I am getting this exception
org.hibernate.HibernateException: D:\fax\hibernate.cfg.xml not found
at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1287)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1309)
at hibernate.LabOrderHelper.getDatabaseSesssion(LabOrderHelper.java:55)
at hibernate.Test.main(Test.java:42)
How can I load hibernate.cfg.xml from a different location than the class path?

There is a method public Configuration configure(File configFile) in class Configuration
Try the following, it should work for sure :)
File f = new File("D:\\fax\\hibernate.cfg.xml");
SessionFactory sessionFactory = new Configuration().configure(f).buildSessionFactory();
The difference is you have used a method configure(String resource) which is expecting a resource in a classpath, but where as configure(File configFile) is expecting a File, so you can pass it.

I need to change the sql setting(url) often
I had the same requirement. For switching just the DB connection properties the approach suggested in the accepted answer, though it works, is a bit of a blunt instrument.
Loading a completely different configuration file just to change a few connection properties? Now all the other properties that are common in both are duplicated, and every time you make a change you need to make it in two places.
A better way is to put all the common properties that don't need to change between environments in the default hibernate.cfg.xml, build your Configuration from that as usual, and use the .addProperties() method to add the properties that are environment-specific on top, in this case the connection url. You can load these extra properties from anywhere you like.
public SessionFactory buildSessionFactory() {
return getConfiguration().buildSessionFactory();
}
private Configuration getConfiguration() {
Configuration config = new Configuration.configure(); // load the base config from the default hibernate.cfg.xml
return config.addProperties(getConnectionProperties()); // add your custom connection props for this environment on top
}
private Properties getConnectionProperties() {
Properties connectionProps = new Properties();
connectionProps.put("hibernate.connection.url", getConnectionUrl());
// possibly add other props like hibernate.connection.username, hibernate.connection.password
return connectionProps;
}
private String getConnectionUrl() {
// get your connection URL from wherever you like
}

Hibernate XML configuration file “hibernate.cfg.xml” is always put at the root of your project classpath, outside of any package. If you place this configuration file into a different directory, you may encounter the following error :
Initial SessionFactory creation failed.org.hibernate.HibernateException:
/hibernate.cfg.xml not found
To ask Hibernate look for your “hibernate.cfg.xml” file in other directory, you can modify the default Hibernate’s SessionFactory class by passing your “hibernate.cfg.xml” file path as an argument into the configure() method:
SessionFactory sessionFactory = new Configuration()
.configure("/com/example/persistence/hibernate.cfg.xml")
.buildSessionFactory();
return sessionFactory;
Full Example in HibernateUtil.java, to load “hibernate.cfg.xml” from directory “/com/example/persistence/“.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// load from different directory
SessionFactory sessionFactory = new Configuration().configure(
"/com/example/persistence/hibernate.cfg.xml")
.buildSessionFactory();
return sessionFactory;
} 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();
}
}

supplementing the accepted answer,
You can load hibernate.cfg.xml from a different directory (not necessarily the classpath) using the configure(File configFile) method that takes the hibernateConfig File argument.
(note, am using hibernate 4.3.7)
The advantage is, if you have no access to the war file but can get access to the hibernate file in a different directory, say for maintenance.
Like this:
String hibernatePropsFilePath = "/etc/configs/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Related

Getting name from hibernate for class

I have a project with supporting XML-config. Now we wanna add hibernate config for entities via annotation. Seems it possible and works (correct me if I am mistaken). The issue is that our system
private String entityName() {
String name = null;
try {
String longName = getDaoFactory().getSessionFactory().getClassMetadata(entityClass).getEntityName();
name = longName.substring(longName.lastIndexOf(".") + 1);
} catch (Exception ex) {
log.error("Exception getting name from hibernate for class: " + entityClass);
name = null;
}
return name;
}
This method works well for entities with xml-config, but how to get a name for an entity which is configurated by annotation?
Thank you in advance for any recommendation and suggestion :)
UPD:
from init session factory method:
Configuration configuration = new Configuration();
configuration.addResource("resources/administrator/queries.hbm.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration
.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
setSessionFactory(sessionFactory);
return configuration;
I created a session Factory like this.
public static SessionFactory buildSessionFactoryFromAnnotatedClasses(){
StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder().applySettings(// pass org.hibernate.cfg.Configuration object here)
.getProperties()).build(); // Configuration object has properties
MetadataSources sources = new MetadataSources(standardRegistry);
sources.addAnnotatedClass(MyClass.class);// MyClass is your java annotated class
Metadata metaData = sources.getMetadataBuilder().build();
return metaData.getSessionFactoryBuilder().build();
}

Hibernate found hibernate.cfg.xml but method no

yeah i know what you think that i didn't try resolve, check other topics etc. I read other topics but anywhere I can't find same problem as my.
Console give me this stacktrace:
20-Dec-2016 20:59:19.482 INFO [http-nio-8080-exec-7]
org.hibernate.cfg.Configuration.configure HHH000042: Configuring from file:
hibernate.cfg.xml
Enitial SessionFactory creation failedorg.hibernate.HibernateException:
could not find file: spring-mvc-angularjs-
master\src\main\java\com\user\springmvcangularjs\hibernate.cfg.xml
Well in first line i got information about that springe configuring from file hibernate.cfg.xml, but when i try connect with database i have error "could not find file".
I try all solutions but any helped me.
My code:
HibernateUtill class
public class HibernateUtil {
private static final SessionFactory ourSessionFactory;
private static final ServiceRegistry serviceRegistry;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Enitial SessionFactory creation failed" + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return ourSessionFactory;
}
}
Method in UserService class:
#Override
public void save(User user)
{
HibernateUtil hibernateUtil = new HibernateUtil();
SessionFactory sessFact = hibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
org.hibernate.Transaction tr = session.beginTransaction();
System.out.println(tr.isActive());
session.save(user);
tr.commit();
sessFact.close();
}
PS I have hibernate.cfg.xml file in spring-mvc-angularjs-master/src/main/java

How to configure hibernate config file to have multiple instances from same database?

I have multiple instances on db2. How can I configure hibernate config file so that I can use all of them?
You can specify it by schema element while defining table for your entity.
#Table(name="TABLE_NAME", schema="SCHEMA_NAME")
Else, you can use separate EntityManager pointing to respective schema & then use the same entity, as their structure is similar.
You can have separate configuration files for each schema & then build SessionFactory from it, below is some pseudo-code for it.
SessionFactory sf_1 = new Configuration().configure("schema1config.cfg.xml").buildSessionFactory();
SessionFactory sf_2 = new Configuration().configure("schema2config.cfg.xml").buildSessionFactory();
session_1 = sf_1.openSession(); //-- Similarly for other
You can refer this link for further details to map multiple schema, but it isn't hibernate specific.
Credit goes to #Nayan Wadekar
Resource Link:
How to connect to multiple databases in Hibernate
Found solution over link as per my requirement:
Setting properties programmatically in Hibernate
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
Properties c = new Properties();
c.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
c.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
c.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/mydiscou_billing?zeroDateTimeBehavior=convertToNull");
c.setProperty("hibernate.connection.username", "root");
c.setProperty("hibernate.connection.password", "123");
c.setProperty("hibernate.connection.autoReconnect", "true");
c.setProperty("connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");
c.setProperty("c3p0.min_size", "5");
c.setProperty("c3p0.max_size", "20");
c.setProperty("c3p0.timeout", "1800");
c.setProperty("c3p0.max_statements", "100");
c.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
sessionFactory = new AnnotationConfiguration().setProperties(c).configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Hibernate NoClassDefFoundError org.hibernate.cfg.Configuration in Java web application

I' m developing a simple JSF application which uses Hibernate. I imported all required libraries to WEB-INF/lib folder and also point them in classpath. But when I tried to compile it I got error:
Here is code where I create SessionFactory and use it:
private static SessionFactory buildSessionFactory()
{
try
{
Configuration configuration = new Configuration();//This line
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry( );
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
catch (Exception e)
{
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return buildSessionFactory();
}
And here I use it:
public static void saveUser( String title)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Client client = new Client();
......
So what am I doing wrong? How can I fix this?
The javax.transaction.SystemException is in the jta-x.y.jar (x.y is the required version for the version of Hibernate you use). It should be in your classpath.
Hibernate requires a lot of libraries. To manage the dependencies, you should use something like Maven or Ivy.

Error while creating SessionFactory object form hibernate.cfg.xml

i am creating a HibernateUtil.java class to return SessionFactory Object. but it's giving Error "The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class". my code is as --
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
#SuppressWarnings("deprecation")
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
it seems you didn't include jre system liberary in build path.
Right click on project --> Properties --> select Java Build Path --> Libraries -->
Add Library --> JRE System Library --> Next --> Workspace default JRE --> Finish

Categories

Resources