I spent last night trying to figure this out. I have a HSQLDB server running and I can connect to it using the JDBC driver. The next part of the assignment is to do the same thing but using the Spring framework. I declared my beans, created my DAO classes, and the program does not connect to the server. Since it is our first time using the JdbcTemplate, we are not supposed to do autowiring. Here are the files I have:
JdbcUserDAO
public class JdbcUserDAO extends JdbcDaoSupport
implements UserDAO {
public User getUserWithId(int id) {
return new User(1,"gamda","test");
}
public int howManyUsers() {
JdbcTemplate test = getJdbcTemplate();
System.out.println("Got template");
try {
getConnection();
System.out.println("Got connection");
} catch (Exception e) {
System.out.println("Not connecting");
}
int result = test.queryForInt("select count from users");
System.out.println("Query success");
return result;
}
}
beans.xml (on the same folder as my .java files, if it makes a difference)
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="userDAO" class="com.project2.db.JdbcUserDAO">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="questionDAO" class="com.project2.db.JdbcQuestionDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="answerDAO" class="com.project2.db.AnswerDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="url" value="jdbc:hsqldb:hsql://localhost/cpsc476;ifexists=true"/>
<property name="username" value="SA"/>
<property name="password" value="Passw0rd"/>
</bean>
</beans>
build.xml for ant:
<project
name="DB_Access"
default="compile"
xmlns:artifact="antlib:org.apache.maven.artifact.ant">
<target name="init">
<mkdir dir="classes" />
</target>
<target name="clean">
<delete dir="classes" />
<delete dir="jar" />
</target>
<target name="compile" depends="init">
<javac srcdir="src"
destdir="classes">
<classpath refid="dependency.classpath" />
</javac>
</target>
<target name="run" depends="compile">
<java classname="com.project2.db.ListQuestionsAndAnswers">
<classpath>
<path refid="dependency.classpath" />
<path location="classes/" />
</classpath>
</java>
</target>
<target name="jar" depends="compile">
<mkdir dir="jar" />
<jar destfile="jar/db.jar" basedir="classes">
<manifest>
<attribute name="Main-Class" value="com.project2.db.dbCon" />
</manifest>
</jar>
</target>
<artifact:dependencies
pathId="dependency.classpath"
filesetId="dependency.fileset">
<dependency
groupId="org.springframework"
artifactId="spring-jdbc"
version="3.2.4.RELEASE" />
<dependency
groupId="org.springframework"
artifactId="spring-beans"
version="3.2.4.RELEASE"/>
<dependency
groupId="org.springframework"
artifactId="spring-context"
version="3.0.2.RELEASE"/>
<dependency
groupId="org.hsqldb"
artifactId="hsqldb"
version="2.3.0" />
<dependency
groupId="commons-dbcp"
artifactId="commons-dbcp"
version="1.4" />
</artifact:dependencies>
</project>
And the test class I'm using: Edited after reading the tutorial provided
public class ListQuestionsAndAnswers {
public static int main( String[] args ) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"beans.xml");
JdbcUserDAO test = (JdbcUserDAO) appContext.getBean("userDAO");
int answer = test.howManyUsers();
System.out.println(answer);
return 0;
}
}
When I do "ant run" this is the output: Edited because it's a new error
>[java] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchFieldError: NULL
>[java] at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:194)
>[java] at org.apache.tools.ant.taskdefs.Java.run(Java.java:771)
>[java] at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:221)
>[java] at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:135)
>[java] at org.apache.tools.ant.taskdefs.Java.execute(Java.java:108)
>[java] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
>[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
>[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
>[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
>[java] at java.lang.reflect.Method.invoke(Method.java:606)
>[java] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
>[java] at org.apache.tools.ant.Task.perform(Task.java:348)
>[java] at org.apache.tools.ant.Target.execute(Target.java:435)
>[java] at org.apache.tools.ant.Target.performTasks(Target.java:456)
>[java] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
>[java] at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
>[java] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
>[java] at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
>[java] at org.apache.tools.ant.Main.runBuild(Main.java:851)
>[java] at org.apache.tools.ant.Main.startAnt(Main.java:235)
>[java] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
>[java] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
>[java] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [beans.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchFieldError: NULL
>[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
>[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
>[java] at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
>[java] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
>[java] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
>[java] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
>[java] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
>[java] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
>[java] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
>[java] at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
>[java] at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
>[java] at com.project2.db.ListQuestionsAndAnswers.main(Unknown Source)
>[java] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
>[java] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
>[java] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
>[java] at java.lang.reflect.Method.invoke(Method.java:606)
>[java] at org.apache.tools.ant.taskdefs.ExecuteJava.run(ExecuteJava.java:217)
>[java] at org.apache.tools.ant.taskdefs.ExecuteJava.execute(ExecuteJava.java:152)
>[java] ... 21 more
>[java] Caused by: java.lang.NoSuchFieldError: NULL
>[java] at org.springframework.expression.TypedValue.<clinit>(TypedValue.java:31)
>[java] at org.springframework.expression.spel.support.StandardEvaluationContext.setRootObject(StandardEvaluationContext.java:82)
>[java] at org.springframework.expression.spel.support.StandardEvaluationContext.<init>(StandardEvaluationContext.java:71)
>[java] at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:124)
>[java] at org.springframework.beans.factory.support.AbstractBeanFactory.evaluateBeanDefinitionString(AbstractBeanFactory.java:1312)
>[java] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.evaluate(BeanDefinitionValueResolver.java:225)
>[java] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:312)
>[java] at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
>[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1387)
>[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1128)
>[java] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
>[java] ... 38 more
>[java] Java Result: -1
So I know my JdbcTemplate is not null, but it fails to connect to the database and I don't know how to check the connection or make it connect.
Create a project with a name SpringExample and create a package com. tutorialspoint under the src folder in the created project. Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter. Add Spring JDBC specific latest libraries mysql-connector-java.
There is only a spring-boot-starter-jdbc dependency is required. In Spring JDBC, multiple dependencies need to be configured like spring-jdbc and spring-context. It automatically configures Datasource bean, if not maintain explicitly. If we do not want to use the bean, we can set a property spring.
The JdbcTemplate class executes SQL queries, iterates over the ResultSet , and retrieves the called values, updates the instructions and procedure calls, “catches” the exceptions, and translates them into the exceptions defined in the org. springframwork.
You have defined JdbcUserDAO
as a spring bean with id userDAO
, but you are creating instance of it with new
operator which won't take care of its dependencies
You need to initialize spring bean context and then fetch the bean from context
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With