Archive

Posts Tagged ‘database’

Basic Spring Code with Maven

May 10, 2010 1 comment

This blog shows how we can use a simple maven project and work with Spring to interact with a database.
First, we create a simple project using the maven command..

mvn archetype:generate

We select the maven-archetype-quickstart project (option 15)
Run the command

mvn eclipse:m2eclipse

to create the .classpath and .project files for eclipse.
We will create a file beans.xml in src/main/resources dir. Not creating the beans.xml file in the resources dir will give you the following exception:
Exception in thread “main” org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [beans.xml] cannot be opened because it does not exist

Here is my beans.xml file.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="dataSource">
 <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
 <property name="url" value="jdbc:mysql://localhost:3306/database-name"></property>
 <property name="username" value="root"></property>
 <property name="password" value="root"></property>
 </bean>
 <bean id="template">
 <property name="dataSource" ref="dataSource"></property>
 </bean>
 <bean id="mySQLDao">
 <property name="template" ref="template"></property>
 </bean>
</beans>

Create a main class with the following code:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
MySQLDao mySQLDao = (MySQLDao)context.getBean("mySQLDao");
System.out.println(mySQLDao.queryForDate());

In MySQLDao we have the following code:

 private JdbcTemplate template;

 public Date queryForDate(){
 String sql = "select now() from dual;";
 Date currentDate = (Date)template.queryForObject(sql, Date.class);
 return currentDate;
 }

 public void setTemplate(JdbcTemplate template) {
 this.template = template;
 }

In pom.xml add the following dependencies:

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-core</artifactId>
 <version>2.5.6</version>
 <scope>compile</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jdbc</artifactId>
 <version>2.5.6</version>
 <scope>compile</scope>
 </dependency>
 <dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>2.5.6</version>
 <scope>compile</scope>
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.11</version>
 <scope>compile</scope>
 </dependency>



If the mysql-connector jar is not installed in the local repository , use the following command to install the jar.

mvn install:install-file -DgroupId=mysql -DartifactId=mysql-connector-java -Dversion=5.1.11 -Dfile=mysql-connector-java-5.1.11-bin.jar -DgeneratePom=true -Dpackaging=jar

Running the main class should now give the current timestamp from the database.
To run main from the command line use the following command

mvn exec:java -Dexec.mainClass="com.wordpress.codesilo.Main"

Accessing databases using datasource xml

March 15, 2010 Leave a comment

We will use the previous struts project to setup database access to MySQL running on localhost.
Run the following command to create the .project and .classpath files for Eclipse and import the project in Eclipse

mvn eclipse:m2eclipse

Download the database driver mysql-connector-java-5.1.11-bin.jar from here and save it to the lib folder in this location $JBOSS_HOME/server/web/lib

Create a jboss-web.xml file in the WEB-INF folder with the following content

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
 <resource-ref>
 <res-ref-name>CodesiloDS</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <jndi-name>java:CodesiloDS</jndi-name>
 </resource-ref>
</jboss-web>

In the web.xml file add the following :

 <resource-ref>
 <res-ref-name>CodesiloDS</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 </resource-ref>

Create a datasource xml file and add it to the deploy dir of JBoss.

Here is the content of my file:

<datasources>
 <local-tx-datasource>
 <jndi-name>CodesiloDS</jndi-name>
 <connection-url>jdbc:mysql://localhost:3306/database-name</connection-url>
 <driver-class>com.mysql.jdbc.Driver</driver-class>
 <user-name>username</user-name>
 <password>password</password>
 <min-pool-size>5</min-pool-size>
 <max-pool-size>20</max-pool-size>
 <!-- Typemapping for JBoss 4.0 -->
 <metadata>
 <type-mapping>mySQL</type-mapping>
 </metadata>
 </local-tx-datasource>
</datasources>

Replace database-name, username and password with appropriate values.

To keep things simple to test, we will add an action in struts-config and have the Action class call the database.

In the action class add this

private final String DATABASE_JNDI_SOURCE = "java:CodesiloDS";

and have this in the execute method. (In the real world most of this code would reside in your model and any helper classes.)

public ActionForward execute(ActionMapping mapping, ActionForm form,
 HttpServletRequest request, HttpServletResponse response)
 throws Exception {

 Connection conn = null;
 Statement stmt = null;
 ResultSet rs = null;
 String date ="";
 try{
 Context ctx = new InitialContext();
 DataSource ds = (DataSource)ctx.lookup(DATABASE_JNDI_SOURCE);
 if(ds!= null){
 conn = ds.getConnection();
 stmt = conn.createStatement();
 rs = stmt.executeQuery("select curdate() from dual;");
 if(rs.next()){
 date = rs.getString(1);
 }
 }
 }
 catch(Exception e){
 ---- code here----
 }
 finally{
 try{
 rs.close();
 stmt.close();
 conn.close();
 }
 catch(Exception e){
 ---- code here -----
 }
 }
 System.out.println("This is a test: " + date);
 return mapping.findForward("success");
 }

Once we call the action, we should see the current date printed on the console.