Setting V$SESSION.program property on Glassfish JDBC Connection Pool - oracle

my Java EE App is deployed on Glassfish 3.0.1, and uses a JDBC Connection Pool to Connect to an Oracle 9i database. I am using JPA to read/write data to the database, which is working fine. However, to get better reporting regarding the load this app is putting on the database, I want to set the V$SESSION.program column for use by oracle.
From various google searches (eg. http://forums.oracle.com/forums/thread.jspa?messageID=3271623) it looks like I should just be able to add this as a property, the same as you would set any other property. So I have tried this by changing the domain.xml file for Glassfish (see below), and the V$SESSION.program property is now set on the JDBC connection pool when I view it using the Glassfish Admin Console (When I start up the glassfish server, go to the admin page and browse to Resources->JDBC->Connection Pools->MyConnectionPool->Additional Properties I can see an entry for V$SESSION.program set appropriately).
However, when I query the Oracle Database for the connections (SELECT * FROM V$SESSION), they have the same V$SESSION.program as before (which is "JDBC Thin Client"), rather than the one I set in the domain.xml and which I can see as a property of the JDBC Connection Pool on the Glassfish Admin Page.
The resources section of my domain.xml is below:
<resources>
<jdbc-connection-pool pool-resize-quantity="4" max-pool-size="16" datasource-classname="oracle.jdbc.pool.OracleDataSource" res-type="javax.sql.DataSource" steady-pool-size="4" name="mydatabasename">
<property name="datasourceName" value="OracleConnectionPoolDataSource" />
<property name="databaseName" value="mydatabasename" />
<property name="password" value="mypassword" />
<property name="portNumber" value="1521" />
<property name="serverName" value="myservername" />
<property name="url" value="jdbc:oracle:thin:#myservername:1521:mydatabasename" />
<property name="user" value="myuser" />
<property name="v$session.program" value="MyGlassfishApp" />
</jdbc-connection-pool>
<jdbc-resource pool-name="mydatabasename" jndi-name="jdbc/mydatabasename" />
</resources>
And my Persistence.xml is as below (I've deleted all the <class>...</class> lines):
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="Persistence-ejb" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/mydatabasename</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.query.timeout" value="60"/>
<property name="javax.persistence.lock.timeout" value="60"/>
<property name="javax.persistence.target-server" value="SunAS9"/>
<!-- Disable caching so we always use the DB directly -->
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.query-results-cache" value="false"/>
</properties>
</persistence-unit>
</persistence>
EDIT:
I have tried v$session.program, V$SESSION.PROGRAM and V$SESSION.program - none have worked though... I have also tried setting the V$SESSION.program property on the EntityManager, but that didn't work (I didn't really expect it to since from what I understand the EntityManager properties are only to do with the JPA layer, not the underlying connection to the Database - but I'm trying stuff out of desperation...)
I also tried using a SessionCustomizer as suggested here. The SessionCustomizer code I used is below:
public class ProgramSessionCustomizer implements SessionCustomizer {
private static Logger logger = Logger.getLogger(ProgramSessionCustomizer.class);
#Override
public void customize(Session s) throws Exception {
logger.error("ProgramSessionCustomizer setting v$session.program");
s.getDatasourceLogin().setProperty("v$session.program", "MYprogramTEST");
logger.error("ProgramSessionCustomizer has set v$session.program");
}
}
I then set the SessionCustomizer in the persistence.xml by adding the property:
<property name="eclipselink.session.customizer" value="persistence.config.ProgramSessionCustomizer"/>
I can see the log lines, so the Customizer is definitely being called. However, I don't see the program set in the database, and I don't even see it set when I browse to the JDBC connection pool properties on the Glassfish Admin Console (which, as I said above, I do see when I set the property using the glassfish domain.xml)
Again, any more suggestions would be very welcome as I'm at a loss!

I finally found out how to set this connection property in WebSphere 8 too for a XA datasource. It can be set in the WebSphere admin console:
Resources > JDBC providers > [Oracle JDBC Driver (XA)] > Data Sources > [data source name] > Custom properties
Just add there a property with a key: connectionProperties and its value: v$session.program:PUT_YOUR_NAME_HERE

This works for me using Spring. It should works for yours Java EE app as well. The idea is to set the v$session param indirectly via properties passed to connectionProperties property
<bean class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="URL" value="${configDb.url}"/>
<property name="user" value="${configDb.user}"/>
<property name="password" value ="${configDb.password}"/>
<property name="connectionCachingEnabled" value="true"/>
<property name="connectionProperties">
<value>v$session.program:PUT_YOUR_NAME_HERE</value>
</property>
</bean>

Related

How to configure Oracle's Database Network Encryption with MyBatis?

I have a requirement to encrypt the data in transit between the web server and the database server using Mybatis as the persistence framework.
The database server is Oracle 12c Enterprise Edition Release 12.1.0.2.0 - 64bit. I am using the ojdbc7.jar driver.
I am able to establish an encrypted connection as described here... https://docs.oracle.com/database/121/DBSEG/asojbdc.htm#DBSEG9613. However, I have not been able to do so through MyBatis. I am setting the connection properties in the mybatis-config.xml file. Below are the contents of that file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC '-//mybatis.org//DTD Config 3.0//EN' 'http://mybatis.org/dtd/mybatis-3-config.dtd'>
<configuration>
<settings>
<setting name="lazyLoadingEnabled" value="false" />
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#//<server>:<port>/<service>"/>
<property name="username" value="<username>"/>
<property name="password" value="<password>"/>
<property name="poolMaximumActiveConnections" value="20"/>
<property name="poolMaximumIdleConnections" value="10"/>
<property name="poolMaximumCheckoutTime" value="180000"/>
<property name="poolPingQuery" value="select 0 from dual"/>
<property name="poolPingEnabled" value="true"/>
<property name="poolPingConnectionsNotUsedFor" value="1800000"/>
<property name="CONNECTION_PROPERTY_THIN_NET_ENCRYPTION_LEVEL" value="REQUIRED"/>
<property name="CONNECTION_PROPERTY_THIN_NET_ENCRYPTION_TYPES" value="AES256"/>
</dataSource>
</environment>
</environments>
</configuration>
The last two property elements are my attempt at configuring an encrypted connection. Without them I am able to connect successfully without encryption. With the last two property elements I just get an error:
Caused by: org.apache.ibatis.exceptions.PersistenceException: ###
Error building SqlSession. ### The error may exist in SQL Mapper
Configuration ### Cause: org.apache.ibatis.builder.BuilderException:
Error parsing SQL Mapper Configuration. Cause:
org.apache.ibatis.datasource.DataSourceException: Unknown DataSource
property: CONNECTION_PROPERTY_THIN_NET_ENCRYPTION_TYPES
Does anybody know how to solve this?
The names of the JDBC properties are not quite right. Note that they can be found in the JavaDoc under oracle.jdbc.OracleConnection. You can try these:
EDIT: as Chris explained in this comments MyBatis requires the driver's property name to be prefixed with "driver".
<property name="driver.oracle.net.encryption_client" value="REQUIRED"/>
<property name="driver.oracle.net.encryption_types_client" value="(AES256)"/>

Using jndi with jpa and spring on glassfish

I have a web application that runs on glassfish 3.1. I am using JPA (Hibernate) configured with spring.
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myPU">
<class>org.myCompany.entities.Class1</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
This is part of my ApplicationContext.xml:
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/myDataSource" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="myPU" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
In addition i have declared my datasource in the glassfish server (jdbc connection pool and recourse)
and the JNDI name is "jdbc/myDataSource". The issue is that on my local installation of glassfish, published via the glassfish plugin for eclipse, it works fine BUT when i deploy the war file manually on an installation of glassfish (i tried on my VPS - CentOS) then i get this error:
Error occurred during deployment: Exception while preparing the app : Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused. Error Code: 0. Please see server.log for more details.
For some reason, the application is using the default derby datasource of glassfish and not my defined datasource. anyone knows why and how to overcome this?
Did you configure your JDBC Resource to use the right Connection Pool? There is a default derby pool configured. Maybe you just selected the wrong pool for your resource?

Exception while creating EntityManagerFactory - Lookup failed for 'persistence/myPU' in SerialContext

I'm working with Glassfish application server and trying to connect my spring-hibernate web application to my db, I have the following configurations:
In Glassfish I have added a jdbc connection and send a successful ping to the DB.
I also added a JDBC resource (in glassfish) with jndi name: jdbc/myResource. This resource is under the connection pool in which I have created and tested (in step 1).
My EntityManaget is annotated with #PersistenceContext:
#PersistenceContext(unitName = "myPU")
protected EntityManager entityManager;
Under \src\main\resources\META-INF\ I created my persistence.xml file:
<persistence-unit name="myPU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myResource</jta-data-source>
<properties>
<!-- Glassfish transaction manager lookup -->
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"></property>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.default_schema" value="PUBLIC" />
<property name="hibernate.format_sql" value="true" />
<!-- Validates the existing schema with the current entities configuration -->
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
This is how my applicationContext looks like:
bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<jee:jndi-lookup id="emf" jndi-name="persistence/myPU" />
<!-- In order to enable EntityManager injection -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="persistence/myPU" />
</map>
</property>
</bean>
In my web.xml I have:
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/myPU</persistence-unit-ref-name>
<persistence-unit-name>myPU</persistence-unit-name>
When I publish I keep getting:
No bean named 'myPU' is defined. Please see server.log for more details.
Why is it looking for the persistence unit as a bean?
Any ideas what am I doing wrong?
Thanks in advance
Resolved - I added transaction-type="JTA" to my persistence.xml.
For some reason I was under the impression that if I'm specifying a jta-data-source in my persistence.xml the default transaction-type should be "JTA", maybe it isn't. I don't really understand the relation of the exception I had to this solution but at the moment my persistence.xml has the following line:
<persistence-unit name="myPU" transaction-type="JTA">
And it works like a charm.

Spring + Spring Data JPA Configuration

currently I'm fooling around with a Spring setup. My goal is to use JPA to get access to a Websphere datasource using it's JNDI name. I'm using Spring Data JPA to make life easier for me and worked through some tutorials to get the basic idea.
Bad thing: none of those is talking about the Spring configuration for my JPA szenario + I never worked with JPA / JDBC before.
So I hope you can help me out here. I got 2 configuration files:
applicationContext.xml
<bean id="txManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="eManager" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"></bean>
Since i'm using the #Transactual annotion within my code, i'm using the annotation-driven tag for the txManager. I'm just not really sure what else i should configure for the txManager and what the sessionFactory tag is doing. Is there any documentation for all supported XML tags? Am I missing a importent tag for my szenario?
Same about eManager - not sure if thats right in any way.
persistence.xml
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="spring-jpa">
<jta-data-source>jdbc/myJNDI</jta-data-source>
</persistence-unit>
</persistence>
Same thing here: don't really know what i'm doing. I know i need a persistence unit / provider. I know that many are using hibernate for this, but i would like to stay native and use pure JavaEE / Spring if possible.
I'm just not sure how to configure that.
Currently my project is crashing, telling me: "JPA PersistenceProvider returned null"
The best way is to obtain the EntityManagerFactory from the JNDI via Spring's JNDI support:
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/myPersistenceUnit" />
<jpa:repositories base-package="com.acme.repositories" />
<tx:jta-transactionManager />
This will cause the transaction manager being used from the application server as well. You can also try to setup a JpaTransactionManager and wire the EntityManagerFactory obtained from JNDI into it. You can pull even more configuration into your Spring config files if you only lookup the datasource through an <jee:jndi-lookup /> namespace element and follow the further configuration instructions in the Spring Data JPA reference documentation. Nevertheless it's usually better to use the container resources you can actually get if you decide to use container resources at all.
I just started working with Spring, jpa mysql etc... and I might be able to help you out.
I'll show you the way that I have my configuration right know.
I'm using hibernate by the way for my database connection, I've never did it without so no help from me there :)
My configuration:
Spring-config.xml:
<context:component-scan base-package="com.MYPACKAGE"/>
<!-- To find all your controllers -->
<tx:annotation-driven/>
<!-- This will pickup all your #Transactional annotations-->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- These are my database config files-->
Datasource.xml:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/DATABASENAME"/>
<property name="username" value="USERNAME"/>
<property name="password" value="PASSWORD"/>
</bean>
Hibernate.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
</bean>
I left out the standard xml text that you need to include at the top of your .xml files, but I trust you to work that out yourself ;)
This setup works for me and I hope it can help you out!
If you have any question regarding this post please let me know!
Good luck!
for those using JBoss, the jndi names can be set in persistence.xml properties like this:
<persistence-unit name="punit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/myDS/jta-data-source>
<class>com.company.model.Document</class>
<class>com.company.model.DocumentIndividual</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> -->
<property name="javax.persistence.logging.level" value="INFO" />
<property name="hibernate.show_sql" value="true" />
<property name="jboss.entity.manager.jndi.name" value="java:/my_em"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:/my_emf"/>
</properties>
</persistence-unit>
as described in here section 4.4.2

Spring DB2 JPA Entity Manager Problem

I'm trying to configure Spring, JPA and DB2 in order to have the entity manager instance to be used in my spring controllers but according how I have configured Spring this not happens.
These are the two attempts of configuration of spring:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" />
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="em" />
</bean>
<bean id="em"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fileUtility" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="database" value="DB2" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
the second is this:
<!-- Entity manager factory bean. -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sample" />
</bean>
<!-- Entity manager bean. -->
<bean id="em" factory-bean="entityManagerFactory"
factory-method="createEntityManager" />
and the entity manager is injected in this way:
<bean id="messageService" class="utilities.services.impl.MessageServiceImpl">
<property name="entityManager" ref="em" />
</bean>
but I have always this exception:
Caused by: java.lang.IllegalArgumentException: methods with same signature createEntityManager() but incompatible return types: [interface com.ibm.websphere.persistence.WsJpaEntityManager, interface org.apache.openjpa.persistence.OpenJPAEntityManagerSPI]
I don't know how can be fixed. Has anyone encountered this problem?
Thanks in advance.
[EDIT]
This is my persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<persistence-unit name="fileUtility"
transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:db2://localhost:50000/db2admin" />
<property name="openjpa.ConnectionDriverName" value="COM.ibm.db2.jdbc.app.DB2Driver" />
<property name="openjpa.ConnectionUserName" value="db2admin" />
<property name="openjpa.ConnectionPassword" value="XXXX" />
<property name="openjpa.FlushBeforeQueries" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
<persistence-unit name="fileUtility2" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>file_ds</jta-data-source>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72"/>
</properties>
</persistence-unit>
</persistence>
WebSphere has a JPA implementation bundled. So no need to add openjpa to your lib. In fact, WebSphere is using OpenJPA, so you are not losing anything. Look here for more details
When using a jda-data-source, you need to have transaction-type="JTA". Also, you should not specify connection properties - they are specified in the datasource.
And get rid of the <provider> - the document I linked says:
If no JPA provider is configured in the element of the persistence.xml file within an EJB module, the default JPA provider that is currently configured for this server is used
I believe you're doing the wrong configuration, because you're configuring it "à la Tomcat". If you're using a Java EE application server, such as WAS, you should:
In Spring application context xml file
configure the DAO bean by a <bean> definition
configure the JNDI definition for the datasource created in the application server via a
<jee:jndi-lookup>
definition; the
name
attribute should be
persistence/XXX, where XXX shall match the
<persistence-unit name="XXX" transaction-type="JTA">
in persistence.xml file
The id attribute in the
<jee:jndi-lookup id=YYY> should point to the
name=YYY parameter of the Entity Manager definition in the DAO, this is to say,
#PersistenceContext(name=YYY) EntityManager em;
Specify
<tx:annotation-driven /> and
<tx:jta-transaction-manager />
In file
web.xml of your web app you should include a definition using the xml tag
<persistence-unit-ref> whose
<persistence-unit-ref-name> parameter shall be the
persistence/XXX JNDI name as specified in persistence.xml (shown above).
Finally, you should create a JNDI definition in the application server (AS dependant) that defines the JNDI name for the JDBC connection. This name should match the
<jta-data-source> xml tag in the persistence.xml file, and it is the only link between the JPA definition and the JDBC defined in the application server.
To round up:
Application Context Spring file
<bean class="DAO implementation class" />
<jee:jndi-lookup id="YYY" jndi-name="persistence/XXX" />
<tx:annotation-driven />
<tx:jta-transaction-manager />
persistence.xml file
<persistence-unit name="XXX" transaction-type="JTA">
<jta-data-source>jdbc/DSN</jta-data-source>
</persistence-unit>
web.xml file
...
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/XXX</persistence-unit-ref-name>
</persistence-unit-ref>
...
DAO (only #PersistenceContext shown)
...
#PersistenceContext(name = "YYY")
EntityManager em;
...
Application Server: jdbc/DSN links to the connection definition, where the driver for the DBM is. Depends on both the AS and the DBM used.
Thus, you may see the connection between the DAO -> Spring Application Context file -> persistence.xml and web.xml files -> Application Server JNDI names. IF you're using a full Java EE application server (such as WAS, Weblogic or GlassFish) you don't have to use Spring interface modules; only defnitions in the app server (see Spring documentation, section 12.6.3).

Resources