Hibernate fails to open Connection with Oracle 11g? - java

I made a basic JUnit test to set up this Oracle database on my computer with hibernate. The database works and everything, but trying to hook it up to Hibernate is proving to be a challenge. My config file can be here:
The JUnit test is fairly straight forward and I'm sure it should work, but I'm getting this JUnit failure:
org.hibernate.exception.JDBCConnectionException: Cannot open connection
Any ideas what's wrong with it?
Connection properties in Hibernate config file:
<session-factory>
<property name="hibernate.connection.driver_class">
oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">
jdbc:Oracle:thin:#127.0.0.1:8080/slyvronline</property>
<property name="hibernate.connection.username">
YouNoGetMyLoginInfo</property>
<property name="hibernate.connection.password">
YouNoGetMyLoginInfo</property>
<property name="dialect">
org.hibernate.dialect.OracleDialect</property>
<!-- Other -->
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<!-- Mapping files -->
<mapping class="com.slyvr.pojo.Person"/>
</session-factory>

It's unlikely (but possible) your DB is listening on port 8080. Oracle defaults to port 1521. Start there.
(Since it's a connection issue, relevant portions of Hibernate config are useful; I've edited to reflect.)

There are possible two issues in your connection string
first is the port that Dave Newton, second that after port you should add the sid after : not /.
So try this as a solution:
jdbc:Oracle:thin:#127.0.0.1:1521:slyvronline

When you are connecting with oracle, no need to mention the schema name so the connection URL looks like as below
jdbc:oracle:thin:#<hostname>:<port>:<sid>
ex:
jdbc:oracle:thin:#localhost:1521:xe

Related

How to use SSL encryption when connecting Vaadin App with Hibernate to MariaDB on Azure

I am currently working on a Java 8 app with Vaadin and Hibernate which I am trying to migrate to Azure for testing purposes.
Everything worked out so far except for one thing:
When I activate the require SSL option in The MariaDB on Azure, I can't connect anymore:
Caused by: java.sql.SQLException: SSL connection is required. Please specify SSL options and retry.
Unfortunately I didn't write this app myself and I am not too familiar with neither Vaadin nor Hibernate or even Java in general and how to establish ssl or db connections with those.So I need some help:
This is the JDBC Connection string in the Servlet.java file, where for my understanding the db init happens:
Connection con = DriverManager.getConnection("jdbc:mysql://<username>.mariadb.database.azure.com:3306/<db>?autoReconnect=true", "<username>", "<password>");
which I changed by just adding this to the URL: &useSSL=true&requireSSL=true&verifyServerCertificate=true
Now the app doesn't stop at the DB init anymore but still crashes before the page is fully rendered, with the same error message.
I found a hibernate.cfg.xml with the following content (I removed the mappings to keep it shorter):
<?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>
<!-- Hibernate -->
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- Hikari -->
<property name="hibernate.connection.provider_class">com.zaxxer.hikari.hibernate.HikariConnectionProvider</property>
<property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
<property name="hibernate.hikari.dataSource.url">jdbc:mysql://dbname.mariadb.database.azure.com:3306/db</property>
<property name="hibernate.hikari.dataSource.user">username</property>
<property name="hibernate.hikari.dataSource.password">password</property>
<property name="hibernate.hikari.dataSource.cachePrepStmts">true</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSize">250</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">2048</property>
<property name="hibernate.hikari.dataSource.useServerPrepStmts">true</property>
</session-factory>
</hibernate-configuration>
What do I have to change there to make use of SSL for the connection?
You may try:
<property name="hibernate.hikari.dataSource.url">jdbc:mysql://dbname.mariadb.database.azure.com:3306/db?useSSL=true</property>
Per my understanding, the properties in hibernate.cfg.xml will finally be used to generate a whole connection string. So, if there is no direct property for useSSL, you may add it to the url manually.

How to connect to Oracle 12c PDB using Hibernate

I have created a sample Oracle 12c PDB (Pluggable Data Base) using the instructions from here. How do I connect to this pluggable database using Hibernate application? I am using a sample Hibernate application from here
I changed the hibernate.cfg.xml file as follows:
<?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="connection.url">jdbc:oracle:thin:#localhost:1521:sys</property>
<property name="connection.username">sys as sysdba</property>
<property name="connection.password">helloWORLD12</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="net.codejava.hibernate.Book" />
</session-factory>
</hibernate-configuration>
But I am getting the following error trace when I run the program:
Exception in thread "main" org.hibernate.HibernateException: Error accessing stax stream
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:107)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at net.codejava.hibernate.BookManager.setup(BookManager.java:23)
at net.codejava.hibernate.BookManager.main(BookManager.java:100)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[18,6]
Message: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:604)
at com.sun.xml.internal.stream.XMLEventReaderImpl.peek(XMLEventReaderImpl.java:276)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:103)
... 5 more
Kindly let me know where I am going wrong. There are almost no resources online for using Oracle 12c PDB with Hibernate.
UPDATE 1: I had an extra line of XML code in my config file which lead to the XML parsing error. Now - how do I associate a CDB/PDB with a particular user account, since using the PDB through SYS user is not recommended.
I have a PDB named 'pdb1', and it is associated with sys user account. It is stored at the following location:
D:\app\myusername\virtual\oradata\orcl\pdb1
I created a new user 'c##test' and then created a pdb while logged in to the user 'c##test' using the following command:
create pluggable database pdb3 admin user pdb_admin3 identified by helloWORLD12
file_name_convert=('D:\app\myusername\virtual\oradata\orcl\pdbseed\',
'D:\app\myusername\virtual\oradata\test\pdb3\');
'pdb3' is created successfully, but it is not getting associated to the user 'c##test'.
The error trace I am getting now is as follows: https://pastebin.com/skVMLkqT
The issue is with the syntax you are using. you are using :SID instead of /SERVICE_NAME , so make sure to change this line as :
<property name="connection.url">jdbc:oracle:thin:#localhost:1521/sys</property>
to see which services available, execute lsnrctl service.
Please also note that you are trying to use sys account which is a the
same as root. to avoid future problems, it's best practice to create a
new account an use that instead.
according to your stack trace you missed oracle driver dependency:
ClassNotFoundException: Could not load requested class :
oracle.jdbc.OracleDriver
you should add this dependecy to your pom.xml file,Please take these steps for that:
1- Download ojdbc8.jar from oracle site:
https://www.oracle.com/technetwork/database/features/jdbc/jdbc-ucp-122-3110062.html
2- Install ojdbc8 to your local maven repository:
specify you path instead of Path/to/your/
mvn install:install-file -Dfile={Path/to/your/ojdbc8.jar} DgroupId=com.oracle -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar
3-Add Dependency to Pom.xml
<!-- ORACLE database driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

Hibernate xml file issue

I have set up Tapestry 5 project and all went fine, until I deployed Hibernate. I have created hibernate.xml file and
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/project</property>
<property name="connection.username">root</property>
<property name="connection.password">password12</property>
<property name="connection.pool_size">5</property>
<!-- Print SQL to stdout. -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="generate_statistics">true</property>
<property name="hibernate.archive.autodetection">class, hbm</property>
<property name="hibernate.transaction.flush_before_completion">true</property>
<!-- Mapping files TODO: Classify those mappings in exact order and define the relations between them in entities some time later on.-->
<mapping class="rs.project.com.entities.Fruit"/>
<mapping class="rs.project.com.entities.Article"/>
</session-factory>
and it's OK as far as the implementation of it is concerned. However when I deploy the app it defines me some other config, which can be seen on my trace log, and uses some other xml file, based on the mappings it shows me on the log, and it's about some completely different project I used a while ago. The thing is I can't see what's causing such a behavior, and I am really frustrated. I am using Tomcat Apache Catalina and MySQL for Hibernate. Also, I did some research and found out that persistance.xml file is being used in my project.properties which is kinda strange.
persistence.xml.dir=${conf.dir}
Driver for connecting my app to MySQL is jdbc.mysql.driver.So my goal is to possibly define the matter that causes such behavior here with you, and to solve it.
Thanks in advance for your answers.
If your tomcat log is referring to a different project, maybe your context declaration is not right?
Check your contexts directory (for me it's $Tomcat_home\conf\Catalina\localhost) or the Server.xml (if that's what you're using). Make sure that the context file in the contexts directory is pointing to the right directory/project. This error has happened to me before when a previous project had the same context-name as my current one.

Java Hibernate/C3P0 error: "Could not obtain connection metadata. An attempt by a client to checkout a Connection has timed out."

I'm trying to get some code I was passed up and running. It appears to use the Hibernate framework. I've gotten past most of the errors tweaking the configuration, but this one has me dead stumped.
It's trying to connect to two databases: gameapp and gamelog. Both exist. It seems to have issues connecting to gamelog, but none connecting to gameapp (later in the init, it connects to and loads other DBs just fine). Below, I've pasted the error and exception stack dump.
I imaging there's something else in the configs, so I've also included the configuration file for that db. I know this is very vague, but I'm hoping some pro can see the stupid mistake I'm missing.
<?xml version="1.0" encoding="GBK"?>
<!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="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/gamelog</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="hibernate.jdbc.batch_size">100</property>
<property name="jdbc.fetch_size">1</property>
<property name="hbm2ddl.auto">none</property><!-- update -->
<property name="connection.useUnicode">true</property>
<property name="show_sql">true</property>
<!-- c3p0-configuration -->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.timeout">30</property>
<property name="hibernate.c3p0.idle_test_period">30</property>
<property name="hibernate.c3p0.max_statements">0</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
</session-factory>
</hibernate-configuration>
Exception and stack trace:
2010-04-30 17:50:00,411 WARN [org.hibernate.cfg.SettingsFactory] - Could not obtain connection metadata
java.sql.SQLException: An attempt by a client to checkout a Connection has timed out.
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106)
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:65)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:527)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:76)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1933)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1216)
at com.database.hibernate.util.HibernateFactory.<init>(Unknown Source)
at com.database.hibernate.util.HibernateUtil.<clinit>(Unknown Source)
at com.server.databaseop.goodOp.GoodOpImpl.initBreedGoods(Unknown Source)
at com.server.databaseop.goodOp.GoodOpImpl.access$000(Unknown Source)
at com.server.databaseop.goodOp.GoodOpImpl$1.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:165)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:636)
Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool#ca470 -- timeout at awaitAvailable()
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1317)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525)
... 18 more
If you have set C3P0's "checkoutTimeout" property to something other than 0 you might be timing out too quickly (that was my problem, solution: bumped it to 2000 milliseconds from 500).
Alternatively, there's a workaround for this warning:
Set the hibernate.temp.use_jdbc_metadata_defaults property to false.
Found this in http://www.docjar.com/html/api/org/hibernate/cfg/SettingsFactory.java.html, though there may be side effects of not having Hibernate extract JDBC Metadata defaults.
Actually that's not even an authentication error. Is MySQL even running or bound to localhost?
does telnet 127.0.0.1 3306 work?
if so, install the mysql client on the box and try
mysql --user=root --ip=127.0.0.1
and see what happens
Check if you can connect to the gamelog mysql database on the command line with the root user and no password (!). As a side note, I'd recommend to set a password for root and to use a different account to connect to the database from your application, but that's another story.

Memcached Provider for NHibernate not working

I've been at this for days. I have configure my web/app config to use the second level cache with a Memcached server and the provider from NHContrib. I don't get any exceptions yet in testing I see that it does not use the cache for my queries that I have set cacheable = true.
If I switch the provider to the NHibernate.Cache.HashtableCacheProvider and test it works as expected.
here are the relevant config sections I am using
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler,NHibernate" />
<section name="memcache" type="NHibernate.Caches.MemCache.MemCacheSectionHandler,NHibernate.Caches.MemCache" />
</configSections>
<memcache>
<memcached host="192.168.215.60" port="11211" />
</memcache>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">
NHibernate.Connection.DriverConnectionProvider
</property>
<property name="dialect">
MT.Core.Persistence.Dialect, MT.Core
</property>
<property name="connection.driver_class">
NHibernate.Driver.SqlClientDriver
</property>
<property name="connection.connection_string">
Server=192.168.1.1;Initial Catalog=Test;User ID=TestUser;Password=fakepassword;
</property>
<property name="show_sql">true</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory,NHibernate.ByteCode.LinFu</property>
<property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
<!--<property name="cache.provider_class">NHibernate.Cache.HashtableCacheProvider</property>-->
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
</session-factory>
</hibernate-configuration>
</configuration>
The problem ended up being due to a connectivity problem. I used log4net to log any errors to the console and to the application log. It was then I finally saw the errors regarding connecting to the memcached server. Once the code was promoted to a server in the same location the errors were gone. I should have learned to use log4net ages ago.
For memcache the property is 'default_expiration' not 'expiration'. I am not sure about SysCache. But I have used this property for memcache and it works for me.
Initailly I also faced the same error that CountCet mentioned. The attribute 'expiration' is not recognized by the MemCache provider. Later I checked the code and found that it use the property 'default_expiration' and its default value is 300 sec.
I think that the expiration property should set for the memcache provider on the session factory level and not on the provider configuration like others (SysCache)
<property name="expiration">300</property>

Categories

Resources