using Hibernate and MS SQL with intelliJ IDEA - sql-server

I am using Hibernate/JPA 2.0 with SQL Server and IntelliJ IDEA here's a sample code I made to test the connection:
public class App {
public static final String SELECT_QUERY = "select u from UsersEntity as u where u.userId = :userId";
public static void main(String[] args)
{
String userId = "1";
PersistenceProvider persistenceProvider = new HibernatePersistence();
EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap());
EntityManager entityManager = entityManagerFactory.createEntityManager();
List<UsersEntity> users = entityManager.createQuery(SELECT_QUERY, UsersEntity.class).setParameter("userId", userId).getResultList();
System.out.println(users);
entityManager.close();
}
}
And here's what I receive in the console:
"C:\Program Files\Java\jdk1.6.0_29\bin\java" -Didea.launcher.port=7539 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\alt-string.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jce.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.6.0_29\jre\lib\ext\sunpkcs11.jar;D:\mobitrack\out\production\web;D:\mobitrack\lib\javax.persistence.jar;D:\mobitrack\lib\hibernate-entitymanager-4.2.0.Final.jar;D:\mobitrack\lib\jboss-logging-3.1.0.GA.jar;D:\mobitrack\lib\hibernate-core-4.2.0.Final.jar;D:\mobitrack\lib\antlr-2.7.7.jar;D:\mobitrack\lib\jboss-transaction-api_1.1_spec-1.0.0.Final.jar;D:\mobitrack\lib\dom4j-1.6.1.jar;D:\mobitrack\lib\hibernate-jpa-2.0-api-1.0.1.Final.jar;D:\mobitrack\lib\javassist-3.15.0-GA.jar;D:\mobitrack\lib\hibernate-commons-annotations-4.0.1.Final.jar;D:\mobitrack\lib\tools.jar;D:\mobitrack\lib\sqljdbc4-4.0.2206.100.jar;C:\Program Files\JetBrains\IntelliJ IDEA 12.0.4\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain com.mobitrack.services.App
26 mars 2013 17:44:18 org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
26 mars 2013 17:44:18 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.0.Final}
26 mars 2013 17:44:18 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
26 mars 2013 17:44:18 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: true
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB]
26 mars 2013 17:44:19 org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=sa, password=****, autocommit=true, release_mode=auto}
When debugging I found that it stops at:
EntityManagerFactory entityManagerFactory = persistenceProvider.createEntityManagerFactory("newPersistenceUnit", new HashMap());
Knowing that "newPersistenceUnit" is the name of my persistence unit.
Edit:
Yes it works outside IDEA. And when I use the console in IDEA to query the data it works.
I tried using the next code:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = 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;
}
}
I receive the same as above and the debugging stops at :
sessionFactory = new Configuration().configure().buildSessionFactory();
Edit2:
I used an EntityManager:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
List<AdminsEntity> result = entityManager.createQuery( "from AdminsEntity", AdminsEntity.class ).getResultList();
for ( AdminsEntity event : result ) {
logged = event;
}
entityManager.getTransaction().commit();
entityManager.close();
return logged;
It stops at:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("newPersistenceUnit");
here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="newPersistenceUnit">
<class>com.mobitrack.entities.GroupsEntity</class>
<class>com.mobitrack.entities.ZonesEntity</class>
<class>com.mobitrack.entities.AdminsEntity</class>
<class>com.mobitrack.entities.AlarmsEntity</class>
<class>com.mobitrack.entities.LocationsEntity</class>
<class>com.mobitrack.entities.UsersEntity</class>
<class>com.mobitrack.entities.UserGroupsEntity</class>
<class>com.mobitrack.entities.UserZonesEntity</class>
<class>com.mobitrack.entities.SettingsEntity</class>
<class>com.mobitrack.entities.MessagesEntity</class>
<class>com.mobitrack.entities.ProfilesEntity</class>
<class>com.mobitrack.entities.ProfileZonesEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:sqlserver://localhost:1433;databaseName=MOBITRACKDB"/>
<property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="hibernate.connection.username" value="admin"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory"/>
</properties>
</persistence-unit>
Any ideas?

This problem can be caused by the method breakpoints that slow down debugger.
Please double check that you don't have any method breakpoints set. Disabling toString() evaluation and alternate collections view options in Settings | Debugger may also improve its performance.

Related

No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available

In Java project, I am using Sprig Boot 1.5.3.RELEASE. It is connecting with two databases i.e. MongoDB and Microsoft SQLServer. When I run it with spring-boot:run goal, it works fine. However, when I try to run it with package goal then below error is reported by test cases despite the fact that those test cases are not connecting to SQL Server database:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:467)
.....
.....
MediationTest.java (Java class containing test cases generating above error)
#RunWith(SpringRunner.class)
#DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
#SpringBootTest(classes = { Application.class })
public class MediationTest {
#Autowired
private SwiftFormat swiftFormat;
......................
......................
MsqlDbConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "msqlEntityManagerFactory", transactionManagerRef = "msqlTransactionManager", basePackages = { "com.msql.data" })
public class MsqlDbConfig {
#Bean(name = "msqlDataSource")
#ConfigurationProperties(prefix = "msql.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "msqlEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean msqlEntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("msqlDataSource") DataSource dataSource) {
return builder.dataSource(dataSource)
.packages("com.utils.msql.info")
.persistenceUnit("msql").build();
}
#Bean(name = "msqlTransactionManager")
public PlatformTransactionManager msqlTransactionManager(
#Qualifier("msqlEntityManagerFactory") EntityManagerFactory msqlEntityManagerFactory) {
return new JpaTransactionManager(msqlEntityManagerFactory);
}
}
application.properties
spring.data.mongodb.uri=mongodb://dev-abc-123:27017/db
msql.datasource.url=jdbc:sqlserver://ABC-SQL14-WXX;databaseName=dev
msql.datasource.username=dev
msql.datasource.password=*****
msql.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
msql.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy
spring.jpa.show-sql=true
The spring-boot:run goal is defined by the Mojo included within the spring-boot-maven-plugin project. You can find it here. https://github.com/spring-projects/spring-boot/blob/8e3baf3130220a331d540cb07e1aca263b721b38/spring-boot-tools/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/RunMojo.java.
The requiresDependencyResolution scope is set to Test. This will include the dependencies from each phase on the classpath. Take a look at the specification here. https://maven.apache.org/developers/mojo-api-specification.html
The package goal provided by Maven wouldn't include these additional dependencies on the classpath and I believe that is the cause of your issues.
Spring Boot provides a repackage goal which is what should be used for building out executable spring-boot applications.
However, to get more to the point. I think if you update your test to exclude an additional class it might fix your problem.
#DataMongoTest(excludeAutoConfiguration = {EmbeddedMongoAutoConfiguration.class, HibernateJpaAutoConfiguration.class})

Database name containd dot in jdbc url spring boot

Dear all I am in the unfortunate sitution to connect to an sqlserver 2005 databae that was provided to me and contains o dot (.)
I have setup a configuration for spring boot like
#Configuration
public class CustomConfig {
#Bean
#Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.username("myuname")
.password("mypass")
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3.5;")
.driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.build();
}
}
And of course I get an exception stating com.microsoft.sqlserver.jdbc.SQLServerException: Database '5' does not exist. Make sure that the name is entered correctly.
I have tried in vain the following
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName={REALLY_BAD_NAME_V3.5};")
that gives the same error and
.url("jdbc:sqlserver://10.10.10.10:1433;databaseName=REALLY_BAD_NAME_V3{.}5;")
And gives a malformed url exception after reading these instructions.
Any ideas?

PlayFramework accessing secondary database data with jpa/hibernate

I am trying to connect second db to my webapplication written in PlayFramework2.
I've configured correctly my app. I've added already second source callec crm.
Here is my console log:
--- (RELOAD) ---
[info] play - datasource [jdbc:mysql://localhost/svp] bound to JNDI as DefaultDS
[info] play - datasource [jdbc:mysql://192.168.0.4/scrm_customer] bound to JNDI as CRM
[info] play - database [default] connected at jdbc:mysql://localhost/svp
[info] play - database [CRM] connected at jdbc:mysql://192.168.0.4/scrm_customer
[info] play - Application started (Dev)
I've added to my persistence.xml following:
<persistence-unit name="CRM" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>CRM</non-jta-data-source>
</persistence-unit>
and my configuration for that:
db.default.jndiName=DefaultDS
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/svp"
db.default.user=root
db.CRM.jndiName=CRM
db.CRM.driver=com.mysql.jdbc.Driver
db.CRM.url="jdbc:mysql://192.168.0.4/scrm_customer"
db.CRM.user=root
db.default.logStatements=true
jpa.default=defaultPersistenceUnit
But when I am trying to get some data from second db using code as follow:
List<Customer> allCustomers = (List<Customer>) JPA.em("CRM")
.createQuery("FROM Customer", Customer.class)
.getResultList();
I am getting an error:
[error] play - Cannot invoke the action, eventually got an error: java.lang.RuntimeException: No JPA EntityManagerFactory configured for name [CRM]
[error] application -
! #6kd0136e7 - Internal server error, for (GET) [/SupraADMIN/klienci] ->
play.api.Application$$anon$1: Execution exception[[RuntimeException: No JPA EntityManagerFactory configured for name [CRM]]]
at play.api.Application$class.handleError(Application.scala:293) ~[play_2.10-2.2.4.jar:2.2.4]
at play.api.DefaultApplication.handleError(Application.scala:399) [play_2.10-2.2.4.jar:2.2.4]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$3.apply(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4]
at scala.Option.map(Option.scala:145) [scala-library.jar:na]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3.applyOrElse(PlayDefaultUpstreamHandler.scala:264) [play_2.10-2.2.4.jar:2.2.4]
Caused by: java.lang.RuntimeException: No JPA EntityManagerFactory configured for name [CRM]
at play.db.jpa.JPA.em(JPA.java:34) ~[play-java-jpa_2.10-2.2.4.jar:2.2.4]
at models.Customer.getCRMList(Customer.java:124) ~[na:na]
at controllers.admin.CMS.Customers(CMS.java:157) ~[na:na]
at admin.Routes$$anonfun$routes$1$$anonfun$applyOrElse$24$$anonfun$apply$24.apply(routes_routing.scala:429) ~[na:na]
at admin.Routes$$anonfun$routes$1$$anonfun$applyOrElse$24$$anonfun$apply$24.apply(routes_routing.scala:429) ~[na:na]
at play.core.Router$HandlerInvoker$$anon$7$$anon$2.invocation(Router.scala:183) ~[play_2.10-2.2.4.jar:2.2.4]
[error] application - REGUEST: GET /SupraADMIN/klienci GENERATED ERROR: #6kd0136e7: Execution exception in /home/korbeldaniel/Aplikacje/Eclipse/SVP/modules/common/app/models/Customer.java:124
What do I miss? I've checked official documentation, but nothing usefull found.
Please help
Annotate your controller method with following annotation:
#Transactional(value = "CRM", readOnly = true)
and within controller method perform:
JPA.em().createQuery("FROM Customer", Customer.class).getResultList();
Or if you dont want to use annotation:
List<Customer> customers = JPA.withTransaction("CRM", true, new Function0<List<Customer>>() {
#Override
public List<Customer> apply() throws Throwable {
return JPA.em().createQuery("FROM Customer", Customer.class).getResultList();
}
});
I would strongly recommend using JPA.withTransactionAsync instead.

GWT file not found trouble during database connection

I'm trying to create a GWT app and I'm working with a local postgreSQL Database.
I'm working with GWT 2.4 on eclipse Juno.
I implemented in this way the Server-side implementation (TaskServiceImpl):
public class TaskServiceImpl extends ServiceImpl implements TaskService {
#Override
public List<Task> getAllTasks() {
em = this.getEntityManager();
Query q = em.createQuery("SELECT x FROM Task x");
List<Task> list = createList(q.getResultList().toArray(),
new ArrayList<Task>(), em);
em.close();
return list;
}
and this is the Database connection class in the client-side:
public class DatabaseConnection {
public static final TaskServiceAsync taskService;
static {
taskService = GWT.create(TaskService.class);
}
}
I try now to run a getAllTask() in this way
public void onModuleLoad() {
DatabaseConnection.taskService.getAllTasks(new AsyncCallback<List<Task>>() {
#Override
public void onSuccess(List<Task> result) {
System.out.println("Success!");
}
#Override
public void onFailure(Throwable caught) {
System.out.println("Fail!");
}
});
}
And always returns "fail!" and gives me this error:
com.google.appengine.tools.development.LocalResourceFileServlet doGet
WARNING: No file found for: /fantapgl/task
This is my web.xml
<servlet>
<servlet-name>taskServiceImpl</servlet-name>
<servlet-class>fieldProject.server.service.TaskServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>taskServiceImpl</servlet-name>
<url-pattern>/fantaPGL/task</url-pattern>
</servlet-mapping>
to open the connection to the DB I have this code in the persistence.xml:
<properties>
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema()"/>
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver"/>
<property name="openjpa.ConnectionURL" value="jdbc:postgresql://localhost:5432/db" />
<property name="openjpa.ConnectionUserName" value="postgres" />
<property name="openjpa.ConnectionPassword" value="password" />
</properties>
I don't understand where I'm wrong. Can someone plz help me!?
I'm not sure what the problem is. But the error messages seems to suggest you have google appengine enabled. That doesn't make sense because you would only need that if you want to deploy on Google app engine, and you are clearly developing for something else since you can't run PostgreSql on Google appengine.
Futhremore, make sure to close database connections by placing the close in a finally statement and prefer to return specific datatypes; that is, ArrayList instead of List. Otherwise the compiler will generate code for all subclasses of List, because at compile time the compiler can't know what subclass will be used.
Before executing the query:
1) Use jdbc driver
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Your PostgreSQL JDBC Driver is missing! "
+ "Include in your library path!");
e.printStackTrace();
return "error";
}
2) Connect to database
Connection connection = null;
connection =
DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/"YourDB",
"admin",
"pass" );
3) Then Execute the query
if (connection != null) { //Your query }
you need to add #RemoteServiceRelativePath annotation at the begin of the serviceImpl class.
please refer to https://developers.google.com/web-toolkit/doc/latest/tutorial/RPC
or if you have installed google eclipse plugin, create a new project with sample code, you can refer to the sample code as well.

Installing a JNDI datasource for Oracle 11g in Tomcat

I'm on Windows XP, using Tomcat 6 ( I can't upgrade to 7 until the end of the month ).
I've been trying to implement a JNDI database resource to Oracle 11g without success.
A number of other applications on my computer connect just fine with the same database credentials. I made a test JSP using straight up JDBC and put it into Tomcat. It connects just fine too.
I modified a section of my conf/server.xml like this:
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="jdbc/mydb"
auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
factory="oracle.jdbc.pool.OracleDataSourceFactory"
url="jdbc:oracle:thin:#apollo.abc.acme.com:2222:mydatabase"
user="joe"
password="blow"
maxActive="20"
maxIdle="30"
maxWait="-1"/>
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml"/>
</GlobalNamingResources>
My conf/context.xml:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<ResourceLink global="jdbc/mydb" name="jdbc/mydb" type="javax.sql.DataSource"/>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
My conf/web.xml:
<resource-ref>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
This is an excerpt from test JSP, it is crapping out with a nullpointer exception right where it goes to get the JNDI resource:
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
String nsdtestcount = null;
InitialContext ctx = null;
Context envContext = null;
javax.sql.DataSource ds = null;
try
{
ctx = new InitialContext();
envContext = (Context)ctx.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/mydb");
conn = ds.getConnection();
}
catch (Exception e)
{
System.out.println(nameJSP + "Failed to connect to the database: " +
"\n ctx = " + ctx +
"\n envContext = " + envContext +
"\n ds = " + ds +
"\n conn = " + conn );
e.printStackTrace();
}
An excerpt from my log::
INFO: Server startup in 675 ms
testJNDI2.jsp: Failed to connect to the database:
ctx = javax.naming.InitialContext#15356d5
envContext = org.apache.naming.NamingContext#69d02b
ds = null
conn = null
java.lang.NullPointerException
at org.apache.jsp.testJNDI_jsp._jspService(testJNDI_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675)
at java.lang.Thread.run(Thread.java:595)
The code at the line in the stack trace:
at org.apache.jsp.testJNDI_jsp._jspService(testJNDI_jsp.java:114)
ctx = new InitialContext();
envContext = (Context)ctx.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/mydb");
conn = ds.getConnection();
conn = ds.getConnection(); is line 114
From my catalina log:
May 1, 2012 4:17:48 PM org.apache.tomcat.util.modeler.Registry registerComponent
SEVERE: Null component Catalina:type=DataSource,class=javax.sql.DataSource,name="jdbc/mydb"
The contents of my CATALINA_HOME/lib:
C:\tomcat\lib>ls -l
annotations-api.jar
catalina-ant.jar
catalina-ha.jar
catalina-tribes.jar
catalina.jar
ecj-3.3.1.jar
el-api.jar
jasper-el.jar
jasper.jar
jsp-api.jar
log4j-1.2.16.jar
ojdbc14.jar
servlet-api.jar
tomcat-coyote.jar
tomcat-dbcp.jar
tomcat-i18n-es.jar
tomcat-i18n-fr.jar
tomcat-i18n-ja.jar
tomcat-juli-adapters.jar
tomcat-juli.jar
C:\tomcat\lib>
The contents of my JAVA/JDK jre/lib/ext:
C:\Program Files\Java\jdk1.5.0_22\jre\lib\ext>ls -l
activation.jar
dnsns.jar
localedata.jar
log4j-1.2.16.jar
mail.jar
nls_charset12.jar
sunjce_provider.jar
sunmscapi.jar
sunpkcs11.jar
C:\Program Files\Java\jdk1.5.0_22\jre\lib\ext>
Any ideas of what I can try? I would like to make the database resource available to everything running in Tomcat ( it is my dev environment )
Thanks in advance.
There may well be multiple issues but the first is that you have multiple copies of multiple versions of the Oracle JDBC driver in $CATALINA_HOME/lib and $JAVA_HOME/jre/lib/ext.
Step 1 is to remove all instance of the following JARs apart from $CATALINA_HOME/lib/ojdbc14.jar
ojdbc14.jar
ojdbc14_g.jar
ojdbc14dms.jar
ojdbc14dms_g.jar
classes12.jar
classes12.zip
classes12dms.jar
While you are at it, remove $JAVA_HOME/jre/lib/ext/servlet-api.jar as well.
Step 2 is that maxIdle > maxActive does not make any sense. You want maxActive >= maxIdle.
As shown in this example on the tomcat site, I believe "user" should be "username" in your Resource definition.

Resources