-Based on the environment of Last time, I tried to implement the connection to the database.
Open pom.xml and add it to the last line in 
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.45</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
brew install mysql
mysql.server start
CREATE DATABASE sandbox DEFAULT CHARACTER SET utf8;
create table users(id int, name varchar(20));
Please insert appropriately.
Open root-context.xml and add it to the last line in 
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="url">
        <value>jdbc:mysql://127.0.0.1:3306/sandbox</value>
    </property>
    <property name="username">
        <value>root</value>
    </property>
    <property name="password">
        <value></value>
    </property>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource" />
</bean>
HomeController.java
package com.sandbox.app;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
 
		List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM users");
 
		model.addAttribute("data", list.get(0).get("name") );
	
		return "home";
	}
}
home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
	<head>
		<title>Home</title>
	</head>
	<body>
	<h1>
		Hello world!  
	</h1>
	<p>  DB's data is ${data}. </p>
	</body>
</html>
Right-click on the project and run Run> Run on Server. If the following page is displayed, it is successful.

――What is the difference from JPA? -Will you use the ORM library in practice?
Recommended Posts