Hibernate sessionFactory creation and weblogic datasource interaction - java

i saw a lot of example of using hibernate, in particular the session Factory, programmatically
I used this:
private static final SessionFactory sessionFactory = buildSessionFactory();
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;
}
but in my current project i need some different implementation so i removed the FINAL for the sessionFactory constant and i implemented a constructor in order to inizialize this when it is null.
so i have an hibernateUtil abstrac class whit only the SYNCHRONIZED method buildSessionFactory and an implementation class whit this constructor
public myHibernateUtil(){
if (mySessionFactory == null){
mySessionFactory = buildSessionFactory();
}
}
Is it safe?? In your opinion by removing the FINAL for the session factory it is possible to have problem with the number of session and saturate the datasource??
I make this question because i'm getting a strange error for weblogic:
Pool myDatasource is Suspended, cannot allocate resources to applications..
Thanks to all!
EDIT:
Into the Server1-diagnostic.log there are those exception :
[2014-05-21T18:46:41.428+02:00] [Server_1] [NOTIFICATION] [DFW-40101] [oracle.dfw.incident] [tid: [ACTIVE].ExecuteThread: '12' for queue: 'weblogic.kernel.Default (self-tuning)'] [userId: ] [ecid: 356fce390f623850:-983a53a:1461f7d7cb4:-8000-0000000000000b1e,0] An incident has been signalled with the incident facts: [problemKey=BEA-337 [WebLogicServer] incidentSource=SYSTEM incidentTime=Wed May 21 18:46:41 CEST 2014 errorMessage=BEA-337 executionContextId=356fce390f623850:-983a53a:1461f7d7cb4:-8000-0000000000000995]
[2014-05-21T18:46:42.927+02:00] [Server_1] [NOTIFICATION] [DFW-40104] [oracle.dfw.incident] [tid: [ACTIVE].ExecuteThread: '12' for queue: 'weblogic.kernel.Default (self-tuning)'] [userId: ] [ecid: 356fce390f623850:-983a53a:1461f7d7cb4:-8000-0000000000000b1e,0] [errid: 84] [detailLoc: /app/oss/bea-domains/osssbdomain/servers/Server_1/adr/diag/ofm/osssbdomain/Server_1/incident/incdir_84] [probKey: BEA-337 [WebLogicServer]] incident 84 created with problem key "BEA-337 [WebLogicServer]"
Moreover i found a lot of error like this in the server1.log:
Tried all: '1' addresses, but could not connect over HTTP to server: '127.0.0.1', port: '7333'
in the communication beetween oracle service bus and my app.
Thanks!

Related

Fail to connect to MongoDB via HibernateOGM using sessionFactory

I am developing an application that uses Hibernate OGM to work with MongoDB. sessionFactory is used to connect, encountered an error while configuring. Log:
...
2020-12-21 11:09:06 INFO DatastoreProviderInitiator:51 - OGM000016: NoSQL Datastore provider: org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider
2020-12-21 11:09:06 ERROR HibernateDataProvider:108 - org.hibernate.service.spi.ServiceException: OGM000072: Unable to configure datastore provider
Class HibernateUtil to get sessionFactory:
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.ogm.cfg.OgmConfiguration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration configuration = new OgmConfiguration();
//assuming the default mongodb settings
configuration.setProperty("hibernate.ogm.datastore.provider",
"MONGODB");
configuration.setProperty("hibernate.ogm.mongodb.host",
"127.0.0.1");
configuration.setProperty("hibernate.ogm.mongodb.port",
"27017");
configuration.setProperty("hibernate.ogm.mongodb.database",
"test");
configuration.setProperty("hibernate.ogm.datastore.create__database",
"true");
sessionFactory = configuration.buildSessionFactory();
}
return sessionFactory;
}
}
How to fix this problem?
You are missing the hibernate-ogm-mongodbdependency: https://mvnrepository.com/artifact/org.hibernate.ogm/hibernate-ogm-mongodb

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 cannot see OJDBC6 driver

I have a problem in my project, I try to configurate hibernate without using hibernate.cfg.xml file, I do it this way:
private SessionFactory buildSessionFactory() {
try {
System.out.println(hostname);
System.out.println(username);
System.out.println(password);
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration()
.addAnnotatedClass(DBUser.class)
.addAnnotatedClass(DBTrustee.class)
.addAnnotatedClass(DBTrusteeUser.class)
.setProperty("hibernate.show_sql", "true")
.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver")
.setProperty("connection.url", "jdbc:oracle:thin:#"+hostname)
.setProperty("connection.username", username)
.setProperty("connection.password", password)
.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect")
.setProperty("hibernate.default_schema", "apps")
.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);
}
}
And it cannot see my OJDBC6 driver which is in my build path, It was seen when I used hibernate.cfg.xml file but when i try to avoid using file I am getting this:
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
lut 12, 2016 7:26:06 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
lut 12, 2016 7:26:06 PM org.hibernate.dialect.Dialect
What am I doing wrong ? I've tried using both of the jdbc driver classes:
oracle.jdbc.driver.OracleDriver
and
oracle.jdbc.OracleDriver
and still no luck :(
My last try, using hibernate 5, taking from the aPI and manual it said.
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties() // configures settings from Configuration object
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
This is the quick start for hibernate 5 , instead of call configure alone, you need to pass the configuration object that you have created with your properties.
I found the solution:
Changing this:
.setProperty("connection.url", "jdbc:oracle:thin:#"+hostname)
.setProperty("connection.username", username)
.setProperty("connection.password", password)
To this:
.setProperty("hibernate.connection.url", "jdbc:oracle:thin:#"+hostname)
.setProperty("hibernate.connection.username", username)
.setProperty("hibernate.connection.password", password)
Solved the problem. Maybe this will help somebody in the future.

How to load hibernate.cfg.xml from different location

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);

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.

Categories

Resources