简体   繁体   English

如何执行Spring JDBC连接并检索数据?

[英]How to perform Spring JDBC connection and retrieve data?

I am creating a Web Application using Java and Spring. 我正在使用Java和Spring创建一个Web应用程序。 I need to connect to MySQL database and retrieve data in Servlet to display in my JSP page. 我需要连接到MySQL数据库并在Servlet中检索数据以显示在我的JSP页面中。 I searched lot and got many examples to connect to database, but nothing works for me 我进行了很多搜索,并找到了许多连接数据库的示例,但对我而言没有任何用处

Here is my applicationContext.xml 这是我的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:batch="http://www.springframework.org/schema/batch"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd    
    http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- 1) USE ANNOTATIONS TO CONFIGURE SPRING BEANS -->
    <context:component-scan base-package="com.app.any" />
    <!-- 2) DATASOURCE, TRANSACTION MANAGER AND JDBC TEMPLATE -->
    <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/mydatabase" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
       <bean>
       <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>
        <bean id="getTargetFields"  class="com.app.myapp.controllers.controllerClasses.GetTargetFields">
       </bean>
    <beans

From my servlet I am calling a class called GetTargetFields . 从我的servlet中,我调用了一个名为GetTargetFields的类。 In that class I want to pass the query and retrieve the data. 在该类中,我想传递查询并检索数据。 But I don't know how to pass. 但是我不知道如何通过。 Tried many examples using the query() method of JdbcTemplate class. 使用JdbcTemplate类的query()方法尝试了许多示例。 But it is showing error as I dont know which class to pass and what is the return type. 但是它显示错误,因为我不知道要传递哪个类以及返回类型是什么。 Its return type is Object . 它的返回类型是Object I tried ResultSet but showed error. 我尝试了ResultSet但显示了错误。

What I want is in my GetTargetFields class I want to pass a select query and return the result and I want to save the result in ResultSet. 我想要的是在我的GetTargetFields类中,我想传递一个选择查询并返回结果,并将结果保存在ResultSet中。

public class GetTargetFields
{


    public void getTargetField()
    {
            // What code should be here?
    }

}

Can anyone help me to code? 谁能帮我编码? Thanks 谢谢

UPDATE 1 更新1

public class GetTargetFields
{
    private JdbcTemplate jdbcTemplate;
    private DataSource dataSource;

    public static ResultSet rs=null;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplate = new JdbcTemplate(this.dataSource);
    }

    public ResultSet getTargetField() // I know the code is wrong. But I tried this
    {
         ResultSet rs=jdbcTemplate.query("SELECT * from employee",
            ResultSet); //shows error. I want to get the result in ResultSet 
                //Or how the data will be stored in *Collector* and I can access each column fields?
     return rs;
    }

}

You are not injecting or autowiring the jdbcTemplate instance into your GetTargetFields class. 您没有将jdbcTemplate实例注入或自动装配到GetTargetFields类中。 It should be either injected like this. 应该这样注入。

<bean id="getTargetFields"  class="com.app.myapp.controllers.controllerClasses.GetTargetFields">
         <property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>

or autowire it using the @Autowired annotation. 或使用@Autowired批注对其进行自动@Autowired

In the current case even though you have a setter method for data source you are neither injecting that as well. 在当前情况下,即使您有用于数据源的setter方法,也不会注入该方法。 You do not need to create a new instance of JdbcTemplate as you have already done the bean definition in app-context file and Spring will instantiate it for you. 您无需创建JdbcTemplate的新实例,因为您已经在应用程序上下文文件中完成了bean的定义,Spring会为您实例化它。 So the correct implementation should be to inject the jdbcTemplate 因此正确的实现应该是注入jdbcTemplate

You need to use the following syntax 您需要使用以下语法

jdbcTemplate.query("", new ResultSetExtractor<Object>() {

    @Override
    public Object extractData(ResultSet rs) throws SQLException,
            DataAccessException {
        //do what ever you want to do with rs
        return null;
    }
});

You will have to either inject your jdbcTemplate object manually using the following: 您将必须使用以下方法手动注入jdbcTemplate对象:

<bean id="getTargetFields" class="com.app.myapp.controllers.controllerClasses.GetTargetFields">
    <property name="jdbcTemplate" ref="jdbcTemplate" />  
</bean>

Then, you can change the class that injects the jdbcTemplate object to: 然后,可以将注入jdbcTemplate对象的类更改为:

public class GetTargetFields {
    private JdbcTemplate jdbcTemplate;
    ...
}

Or use the @Autowired and @Repository annotations. 或使用@Autowired@Repository批注。

Please see the first half of the following Spring reference which shows how can use those two annotations that would take away much of the complexity: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html 请参阅以下Spring参考的上半部分,该参考显示了如何使用这两个注释可以消除很多复杂性: http : //static.springsource.org/spring/docs/3.0.x/spring-framework-reference /html/jdbc.html

You have the following method in your GetTargetFields class 您的GetTargetFields类中具有以下方法

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}

This means that, during your bean initialization, you can give a datasource as a property which will be injected by spring framework. 这意味着在bean初始化期间,您可以将数据源作为属性提供,该属性将由spring框架注入。

<bean id="getTargetFields" class="com.app.myapp.controllers.controllerClasses.GetTargetFields">
    <property name="dataSource" ref="dataSource">    
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM