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.
Related
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;
}
}
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!
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);
I have installed Websphere Network deployment server 7.0.0.0
I have configured a cluster on it.
I have configured a data source on it say ORA_DS this data source using "JAAS - J2C authentication data"
When i test the ORA_DS by clicking on "Test connection" button, the test connection is success.
The issue comes when i try to access this data source using my java code.
Here is my code to access data source and create a connection:
public class DSTester
{
/**
* Return the data source.
* #return the data source
*/
private DataSource getDataSource()
{
DataSource dataSource = null;
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
env.put(Context.PROVIDER_URL, "iiop://localhost:9811");
// Retrieve datasource name
String dataSourceName = "EPLA1";
if (dataSource == null)
{
try
{
Context initialContext = new InitialContext(env);
dataSource = (DataSource) initialContext.lookup(dataSourceName);
}
catch (NamingException e1)
{
e1.printStackTrace();
return null;
}
}
return dataSource;
}
public static void main(String[] args)
throws Exception
{
DSTester dsTester = new DSTester();
DataSource ds = dsTester.getDataSource();
System.out.println(ds);
System.out.println(ds.getConnection());
}
}
Here is the output:
com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource#17e40be6
Exception in thread "P=792041:O=0:CT" java.sql.SQLException: ORA-01017: invalid username/password; logon denied
DSRA0010E: SQL State = 72000, Error Code = 1,017
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:799)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:368)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:275)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:206)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPhysicalConnection(OracleConnectionPoolDataSource.java:139)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:88)
at oracle.jdbc.pool.OracleConnectionPoolDataSource.getPooledConnection(OracleConnectionPoolDataSource.java:70)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper$1.run(InternalGenericDataStoreHelper.java:1175)
at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
at com.ibm.ws.rsadapter.spi.InternalGenericDataStoreHelper.getPooledConnection(InternalGenericDataStoreHelper.java:1212)
at com.ibm.ws.rsadapter.spi.WSRdbDataSource.getPooledConnection(WSRdbDataSource.java:2019)
at com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl.createManagedConnection(WSManagedConnectionFactoryImpl.java:1422)
at com.ibm.ws.rsadapter.spi.WSDefaultConnectionManagerImpl.allocateConnection(WSDefaultConnectionManagerImpl.java:81)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:646)
at com.ibm.ws.rsadapter.jdbc.WSJdbcDataSource.getConnection(WSJdbcDataSource.java:613)
at com.test.DSTester.main(DSTester.java:70)
The code works fine if i replace
ds.getConnection()
with
ds.getConnection("ora_user", "ora_password")
My issue is i need to get the connection without specifying login details for Oracle.
Please help me on this issue.
Any clue will be appreciated.
Thanks
I'd guess it would work if you retrieved the datasource from an application running on the WAS.
Try creating a servlet.
Context initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("EPLA1");
Connection con = dataSource.getConnection();
As within a servlet it is running within WAS it should be fine, if the "Test Connection" works. Running it outside is probably a different context.
I think you need to check all your configuration:
1) Is it application deplyed on cluster or into only one of cluster member?
2) JAAS - J2C authentication data - what is the scope?
Sometimes you need restar all your WAS environment. It depends on resource configuration scope
I'd recomend to you add resource refences for better configuration options.
SeeIBM Tech note
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.