Spring boot with PostgreSQL

本文节选自《Netkiller Java 手札》 作者 netkiller 他的网站 http://www.netkiller.cn

5.15. Spring boot with PostgreSQL

5.15.1. pom.xml

			<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.4.1212</version>
</dependency>			

5.15.2. application.properties

 spring.datasource.platform=postgres
spring.database.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/your-database
spring.datasource.username=postgres
spring.datasource.password=postgres

spring.jpa.database=POSTGRESQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.generate-ddl=true			

5.15.3. Application

			package cn.netkiller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
@EnableMongoRepositories
@EnableJpaRepositories
@EnableScheduling
public class Application {

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

5.15.4. CrudRepository

Model Class

			package cn.netkiller.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer implements Serializable {

	private static final long serialVersionUID = -3009077722242246666L;
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "firstname")
	private String firstName;

	@Column(name = "lastname")
	private String lastName;

	protected Customer() {
	}

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}			

CrudRepository

			package cn.netkiller.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import cn.netkiller.model.Customer;

public interface CustomerRepository extends CrudRepository<Customer, Long>{
	List<Customer> findByFirstName(String firstName);
    List<Customer> findByLastName(String lastName);
}			

5.15.5. JdbcTemplate

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping(value = "/jdbc")
	public @ResponseBody String dailyStats(@RequestParam Integer id) {
		String query = "SELECT id, firstname, lastname from customer where id = " + id;

		return jdbcTemplate.queryForObject(query, (resultSet, i) -> {
			System.out.println(resultSet.getLong(1)+","+ resultSet.getString(2)+","+ resultSet.getString(3));
			return (resultSet.getLong(1)+","+ resultSet.getString(2)+","+ resultSet.getString(3));
		});
	}			

5.15.6. Controller

			package cn.netkiller.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.netkiller.model.Customer;
import cn.netkiller.repository.CustomerRepository;

@Controller
@RequestMapping("/test/pgsql")
public class TestPostgreSQLController {

	@Autowired
	private CustomerRepository customerRepository;

	@RequestMapping("/save")
	public @ResponseBody String process() {
		customerRepository.save(new Customer("Neo", "Chan"));
		customerRepository.save(new Customer("Luke", "Liu"));
		customerRepository.save(new Customer("Ran", "Guo"));
		customerRepository.save(new Customer("Joey", "Chen"));
		customerRepository.save(new Customer("Larry", "Huang"));
		return "Done";
	}

	@RequestMapping("/findall")
	public @ResponseBody String findAll() {
		String result = "<html>";

		for (Customer cust : customerRepository.findAll()) {
			result += "<div>" + cust.toString() + "</div>";
		}

		return result + "</html>";
	}

	@RequestMapping("/findbyid")
	public @ResponseBody String findById(@RequestParam("id") long id) {
		String result = "";
		result = customerRepository.findOne(id).toString();
		return result;
	}

	@RequestMapping("/findbylastname")
	public @ResponseBody String fetchDataByLastName(@RequestParam("lastname") String lastName) {
		String result = "<html>";

		for (Customer cust : customerRepository.findByLastName(lastName)) {
			result += "<div>" + cust.toString() + "</div>";
		}

		return result + "</html>";
	}

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping(value = "/jdbc")
	public @ResponseBody String dailyStats(@RequestParam Integer id) {
		String query = "SELECT id, firstname, lastname from customer where id = " + id;

		return jdbcTemplate.queryForObject(query, (resultSet, i) -> {
			System.out.println(resultSet.getLong(1)+","+ resultSet.getString(2)+","+ resultSet.getString(3));
			return (resultSet.getLong(1)+","+ resultSet.getString(2)+","+ resultSet.getString(3));
		});
	}
}			

5.15.7. Test

curl http://127.0.0.1:7000/test/pgsql/save
curl http://127.0.0.1:7000/test/pgsql/findall
curl http://127.0.0.1:7000/test/pgsql/findbyid?id=1
curl http://127.0.0.1:7000/test/pgsql/jdbc?id=1

原文发布于微信公众号 - Netkiller(netkiller-ebook)

原文发表时间:2017-04-27

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Netkiller

Spring boot with Service

本文节选自《Netkiller java 手札》 5.7. Service 5.7.1. Application @ComponentScan({ "web",...

2775
来自专栏码匠的流水账

chaos-monkey-spring-boot小试牛刀

chaos-monkey-spring-boot是专门为Spring Boot打造的Chaos Monkey

271
来自专栏Netkiller

Java·日期时间处理

本文节选自《Netkiller Architect 手札》 1.4.3. Date 1.4.3.1. SimpleDateFormat public stati...

3384
来自专栏DT乱“码”

ClassPathXmlApplicationContext方式读取配置文件

public interface BeanFactory {   public Object getBean(String id); }   //实现类Clas...

1875
来自专栏Netkiller

Spring boot with Oracle

本文节选自《Netkiller Java 手札》 地址: http://www.netkiller.cn/java/index.html 9.11. Sprin...

2734
来自专栏osc同步分享

springmvc、spring、hibernate整合示例

在mysql数据库中建立一个user表,已对user的增删改查为例,整合springmvc、spring、hibernate。 1.web.xml中的配置:①s...

3098
来自专栏Netkiller

Spring boot with MySQL 实例参考

节选择《Netkiller Java 手札》· Spring 框架 9.7. Spring boot with MySQL 9.7.1. Maven pom.x...

2705
来自专栏web编程技术分享

【Java框架型项目从入门到装逼】第十节 simple-jdbc源码

35010
来自专栏Netkiller

Spring Boot · Mongo Repository

本文节选自《Netkiller Java 手札》 http://www.netkiller.cn/java/ 11.12.5.1. MongoTempla...

3186
来自专栏Netkiller

Phalcon VS Spring 用法对照手册

Phalcon VS Spring 摘要 Phalcon VS Spring 用法对照表 ---- 目录 1. Install 1.1. Phalcon 1.2...

3356

扫描关注云+社区