Hello World

[펌]Getting started with Spring JDBC in a web application 본문

Spring/Boot(4.x)

[펌]Getting started with Spring JDBC in a web application

EnterKey 2016. 1. 10. 11:58
반응형

I have shown you how to setup a basic Spring 3 MVC web application in my previous article. Reusing that project setup as template, I will show you how to enhance it to work with JDBC. With this you can store and retrieve data from database. We will add a new controller and a data service through Spring so you can see how Spring injection and annotation configuration works together.

A direct JDBC based application is easy to setup in comparison to a full ORM such as Hibernate. You don’t need to worry AOP, TranactionManager, Entity mapping and full array of other configurations. On top of the JDK’sjava.jdbc API, the Spring comes with spring-jdbc module that can boots your productively with their well known JdbcTemplate class. Let’s explore how this can be setup and run as web application.

Getting started and project setup

For demo purpose, I will use the in-memory version of H2Database as JDBC store. It’s simple to use and setup. And if you decided to use their FILE or TCP based database, you would simply have to re-set the datasource, and you may continue to explore more.

We will start by adding new dependencies to your existing spring-web-annotation/pom.xml file.

01<dependency>
02   <groupId>com.h2database</groupId>
03   <artifactId>h2</artifactId>
04   <version>1.3.163</version>
05  </dependency>
06  <dependency>
07   <groupId>org.springframework</groupId>
08   <artifactId>spring-jdbc</artifactId>
09   <version>3.2.4.RELEASE</version>
10  </dependency>

With this, you will have access to Spring module classes for configuration. Find the previoussrc/main/java/springweb/WebApp.java file in your existing project and add what’s new compare to below:

01package springweb;
02 
03import org.springframework.context.annotation.Bean;
04import org.springframework.context.annotation.ComponentScan;
05import org.springframework.context.annotation.Configuration;
06import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
07import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
08import org.springframework.web.servlet.config.annotation.EnableWebMvc;
09importorg.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
10 
11import javax.sql.DataSource;
12 
13public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer {
14    @Override
15    protected Class<?>[] getRootConfigClasses() {
16        return new Class<?>[]{ RootConfig.class };
17    }
18 
19    @Override
20    protected Class<?>[] getServletConfigClasses() {
21        return new Class<?>[]{ WebAppConfig.class };
22    }
23 
24    @Override
25    protected String[] getServletMappings() {
26        return new String[]{ "/" };
27    }
28 
29 @Configuration
30    @EnableWebMvc
31    @ComponentScan("springweb.controller")
32    public static class WebAppConfig {
33    }
34 
35 @Configuration
36 @ComponentScan("springweb.data")
37 public static class RootConfig {
38  @Bean
39  public DataSource dataSource() {
40   DataSource bean = new EmbeddedDatabaseBuilder()
41     .setType(EmbeddedDatabaseType.H2)
42     .addScript("classpath:schema.sql")
43     .build();
44   return bean;
45  }
46 }
47}

What’s new in here is we introduced a new RootConfig class that will be loaded inside getRootConfigClasses() method. TheRootConfig is just another Spring annotation based configuration that creates a new Spring context for bean definitions. We’ve created a bean there that will run the in-memory database. The bean returned by the builder also conveniently implemented the javax.sql.DataSource interface, so we can actually inject this into any data service and start using it immediately.

One more cool thing about the Spring embedded database builder is that it also runs any SQL script as part of the startup! For this demo, we will create a PING table in the src/main/resources/schema.sql file. This file is visible to Spring as in root of the CLASSPATH due to Maven standard source structure.

1CREATE TABLE PING (
2  ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
3  TAG VARCHAR(1024) NOT NULL,
4  TS DATETIME NOT NULL
5);

That’s the datasource setup. Now notice that I did not add this datasource Spring bean definition into existingWebAppConfig class. The reason is that we want a separate Spring context to configure all service level beans, while reserving the WebAppConfig for all Spring MVC related beans (such as Controller, URL mapping etc). This helps organize your bean definitions in hierarchical order of Spring contexts; with RootConfig as parent and WebAppConfig as child layers. This also means that all service beans in RootConfig are automatically visible to WebAppConfig; for the purpose of injection etc.

Also notice that with separated config classes, we are able to specify two distinct packages to scan for service components; we use springweb.controller for WebAppConfig and springweb.data for RootConfig. This is important and it can save you some troubles letting Spring auto detecting your all these annotation based components.

Creating Data Service

Now it’s time we use the JDBC, so let’s write a data service class under src/main/java/springweb/data/PingService.java file.

01package springweb.data;
02 
03import org.apache.commons.logging.Log;
04import org.apache.commons.logging.LogFactory;
05import org.springframework.beans.factory.annotation.Autowired;
06import org.springframework.jdbc.core.JdbcTemplate;
07import org.springframework.stereotype.Repository;
08 
09import javax.sql.DataSource;
10import java.util.Date;
11import java.util.List;
12import java.util.Map;
13 
14@Repository
15public class PingService {
16    public static Log LOG = LogFactory.getLog(PingService.class);
17 
18    private JdbcTemplate jdbcTemplate;
19 
20    @Autowired
21    public void setDataSource(DataSource dataSource) {
22        this.jdbcTemplate = new JdbcTemplate(dataSource);
23    }
24 
25    public void insert(String tag) {
26        LOG.info("Inserting Ping tag: " + tag);
27        jdbcTemplate.update("INSERT INTO PING(TAG, TS) VALUES(?, ?)", tag, newDate());
28    }
29 
30    public List<Map<String, Object>> findAllPings() {
31        return jdbcTemplate.queryForList("SELECT * FROM PING ORDER BY TS");
32    }
33}

The service is very straight forward. I expose two methods: one for insert and one for retrieve all Ping data. Noticed that I used @Repository to indicate to Spring that this class is a component service that perform data service. Also note how we inject the DataSource using a setter method, and then instantiate the JdbcTemplate as member field. From that we can take full advantage of the Spring JDBC API for query and update.

A note on logging. Spring core itself uses Apache common-logging, so I reused that API without even explicitly declare them in my pom.xml. If you want to see more details from log output, you should add log4j logger implementation to the project, and it should automatically work. I will leave that as your exercise.

Next we will need to write a Controller that can bring data to web UI page. We will create this undersrc/main/java/springweb/controller/PingController.java file.

01package springweb.controller;
02 
03import org.springframework.beans.factory.annotation.Autowired;
04import org.springframework.stereotype.Controller;
05import org.springframework.web.bind.annotation.PathVariable;
06import org.springframework.web.bind.annotation.RequestMapping;
07import org.springframework.web.bind.annotation.ResponseBody;
08import springweb.data.PingService;
09 
10import java.util.List;
11import java.util.Map;
12 
13@Controller
14public class PingController {
15 
16    @Autowired
17    private PingService pingService;
18 
19    @RequestMapping(value="/ping/{tag}", produces="text/plain")
20    @ResponseBody
21    public String pingTag(@PathVariable("tag") String tag) {
22        pingService.insert(tag);
23        return "Ping tag '" + tag + "' has been inserted. ";
24    }
25 
26    @RequestMapping(value="/pings", produces="text/plain")
27    @ResponseBody
28    public String pings() {
29        List<Map<String, Object>> result = pingService.findAllPings();
30  if (result.size() == 0)
31   return "No record found.";
32 
33        StringBuilder sb = new StringBuilder();
34        for (Map<String, Object> row : result) {
35            sb.append("Ping" + row).append("\n");
36        }
37        return sb.toString();
38    }
39}

In this controller, you can easily see that the Ping data is fetched and updated through our data service by injection. I’ve declared and map URL /ping/{tag} to insert Ping data into the database. Spring has this very nice short hand syntax annotation mapping that can extract parameter from your URL. I allow user to set a simple tag word to be insert as Ping record so we can identify the source in database.

The other controller handler /pings URL is very straight forward; it simply returns all the records from PING table.

For demo purpose, I choose to not use JSP as view, but to return plain text directly from the Controller. Spring let you do this by adding @ResponseBody to the handler method. Notice also we can specify the content type as text/plain as output directly using the annotation.

Testing

To see your hard labor with above, you simply need to run the Maven tomcat plugin. The previous article has shown you an command to do that. Once you restarted it, you should able to open a browser and use these URLS for testing.

Happing programming

From this simple exercise, you can quickly see Spring MVC brings you many benefits; and a lot of fun in developing web application. Spring, by design principles, tends to be developers friendly, boots productivity and un-intrusively in your environment. It’s one of the reason I like to work with it a lot. I hope you enjoy this tutorial and go further explore on your own.

Happy programming!
 




출처: http://www.javacodegeeks.com/2013/10/getting-started-with-spring-jdbc-in-a-web-application.html?utm_content=buffer358fb&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer


반응형
Comments