Search code examples
javaspringtomcatjpajndi

Does JPA require the Datasources come from JNDI?


I'm using Spring in Tomcat for my webapp. My datasources are built in Spring then published to JNDI using org.springframework.jndi.JndiTemplate. This is clunky for a few reasons, but my main problem is that it's difficult to control the database being used (which I want to do for testing). Is it possible to use JPA without using JNDI as a lookup service? Ideally, I'd be able to provide the data sources directly to JPA, or through some other method that doesn't rely on a container for the implementation (I have investigated JNDI implementations that aren't provided by a container, but they're not right for my needs).


Solution

  • You can specify a datasource in your spring configuration file. Here is an excerpt from mine which uses a MySql Database. To view the full configuration file and project view the source on GitHub.

    <!-- Database -->
    <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/to_thought_tutorial" />
        <property name="username" value="tutorial" />
        <property name="password" value="tutorial" />
    </bean>
    
    <!-- Entity Manager -->
    <bean id="entityManagerFactory"
       class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
           <property name="dataSource" ref="datasource" />
           <property name="persistenceUnitName" value="tothought-tutorial" />
    </bean>
    

    I would also encourage you to visit my blog which contains a video describing how to setup a datasource: http://tothought.cloudfoundry.com/post/4

    The Spring documentation also includes examples of how to setup a datasource that does not rely upon JNDI: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/jdbc.html#jdbc-datasource