Find Entity by Primary Key with Spring JDBC in Spring Boot


On the Eclipse, create a Spring Boot project

Enter Project Information:

  • Name: LearnSpringBootWithRealApps
  • Group: com.demo
  • Artifact: LearnSpringBootWithRealApps
  • Description: Learn Spring Boot with Real Apps
  • Package: com.demo

Select the technologies and libraries to be used:

  • JDBC
  • MySQL

Click Next button to show Site Information for project

Click Finish button to finish create Spring Boot project




<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
						http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.demo</groupId>
	<artifactId>LearnSpringBootWithRealApps</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>LearnSpringBootWithRealApps</name>
	<description>Learn Spring Boot with Real Apps</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!-- Spring Framework -->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- Spring JDBC -->
        <dependency>
		  <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!-- MySQL JDBC -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Create a database with the name is learn_spring_boot_with_real_apps. This database have 1 table: Product table

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `price` decimal(10,1) NOT NULL,
  `quantity` int(11) NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `photo` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `featured` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 1', '2.0', 2, 'description 1', 'thumb1.gif', 1);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 2', '1.0', 5, 'description 2', 'thumb2.gif', 1);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 3', '3.0', 9, 'description 3', 'thumb3.gif', 1);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 1', '5.0', 12, 'description 4', 'thumb1.gif', 0);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 2', '7.0', 5, 'description 5', 'thumb1.gif', 1);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 3', '12.0', 2, 'description 6', 'thumb2.gif', 1);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 1', '3.0', 8, 'description 7', 'thumb2.gif', 0);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 2', '4.0', 11, 'description 8', 'thumb3.gif', 0);
INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 3', '2.0', 15, 'description 9', 'thumb2.gif', 1);




spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/learn_spring_boot_with_real_apps
spring.datasource.username=root
spring.datasource.password=123456

Create new package named com.demo.entities. In this package, create a entity class – Product.java, to represent the above table

package com.demo.entities;

import java.io.Serializable;
import java.math.BigDecimal;

public class Product implements Serializable {

	private int id;
	private String name;
	private BigDecimal price;
	private int quantity;
	private String description;
	private String photo;
	private boolean featured;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getPhoto() {
		return photo;
	}

	public void setPhoto(String photo) {
		this.photo = photo;
	}

	public boolean isFeatured() {
		return featured;
	}

	public void setFeatured(boolean featured) {
		this.featured = featured;
	}

}

Create new package named com.demo.dao. Create classes and interface for DAO layer. DAO layer use JDBC technologies manipulate the database

package com.demo.dao;

import com.demo.entities.Product;

public interface ProductDAO {

	public Product find(int id);

}
package com.demo.dao;

import com.demo.entities.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("productDAO")
public class ProductDAOImpl implements ProductDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public Product find(int id) {
		return jdbcTemplate.queryForObject("select * from product where id = ?",
				new BeanPropertyRowMapper<Product>(Product.class), id);
	}

}




Open LearnSpringBootWithRealAppsApplication.java file in com.demo package, call methods from ProductDAO. To show result to console, this class need implements from CommandLineRunner

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.demo.dao.ProductDAO;
import com.demo.entities.Product;

@SpringBootApplication
public class LearnSpringBootWithRealAppsApplication implements CommandLineRunner {

	@Autowired
	ProductDAO productDAO;

	public static void main(String[] args) {
		SpringApplication.run(LearnSpringBootWithRealAppsApplication.class, args);
	}

	@Override
	public void run(String... arg0) throws Exception {

		Product product = productDAO.find(10);
		System.out.println("Id: " + product.getId());
		System.out.println("Name: " + product.getName());
		System.out.println("Price: " + product.getPrice());
		System.out.println("Quantity: " + product.getQuantity());
		System.out.println("Description: " + product.getDescription());
		System.out.println("Photo: " + product.getPhoto());
		System.out.println("Featured: " + product.isFeatured());

	}
}
Id: 10
Name: Laptop 2
Price: 4.0
Quantity: 11
Description: description 8
Photo: thumb3.gif
Featured: false

I recommend you refer to the books below to learn more about the knowledge in this article: