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 条评论
登录 后参与评论

相关文章

来自专栏程序员互动联盟

只有程序员能看懂的笑话

1. 某程序员退休后决定练习书法,于是重金购买文房四宝。一日,饭后突生雅兴,一番研墨拟纸,并点上上好檀香。定神片刻,泼墨挥毫,郑重地写下一行字:hello wo...

3335
来自专栏小狼的世界

惊闻NBC在奥运后放弃使用Silverlight

奥运初始的时候,媒体对于NBC使用Silverlight技术进行了高调的宣传,没想到奥运会结束刚刚三周的时间,NBC就弃用了Siverlight,重新采用Ado...

1052
来自专栏互扯程序

程序猿一定要知道的&过年&习俗

农历正月初一是春节,又叫阴历(农历)年,俗称“过年”。这是我国民间最隆重、最热闹的一个古老传统节日。春节是汉族最重要的节日。 今天是大年三十 辛辛苦苦忙了一年...

2723
来自专栏吉浦迅科技

GDC 2015 NVIDIA首度展示TITAN X GPU

NVIDIA 於剛結束的 2015 年 GDC 遊戲開發者大會上發表稱為「 Thief in the Shadows 」的嶄新虛擬實境體驗內容,「 Thief ...

2687
来自专栏量子位

AI又输了!中国传奇Dota2冠军联手,OpenAI快速进化然并卵

虽说在今年TI8上,中国各队战绩不如以往,不过今天,三支被淘汰队伍的教练+昨天直播的两名中文解说,如愿以偿地在表演赛上吊打了OpenAI。

1697
来自专栏Java帮帮-微信公众号-技术文章全总结

【非技术面试】面试仪表你必须要注意

面试仪表你必须要注意 面试整体情况总结: 第一, 一定要展现出自己积极向上的精神面貌,服装要简洁、简单、大方。整洁就是整齐和干净,面试时穿着的服装必须是熨烫过或...

3254
来自专栏Python专栏

有时间BB,不如想想怎么让别人闭嘴吧

经过上次「SKR!虎扑66万JRS大战3300万吴亦凡护卫队,别逼我拿Python」一事,我发现观众里有很多JRs,「这就是灌篮」一定不陌生。

1033
来自专栏互联资讯

震撼穿越“亿年壶穴、天地奇观”!无人机成功穿越白云山亿年大壶穴!

福安白云山是史志记载的“闽东第一山”。因四季云雾缭绕,弥望如海,故名白云山。说起闽东宁德的风景,大家都不由想起太姥山和白水洋。可大家知道吗?福建福安白云山、屏南...

1194
来自专栏VRPinea

甜蜜地狱,拿起棉花糖冲击枪对战甜甜圈僵尸吧!

3436
来自专栏CDA数据分析师

【戏说大数据】向林彪同志学习数据挖掘

【不打无把握之仗】 林彪从红军带兵时起,身上就有个小本子,上面记载着每次战斗的缴获、歼敌数量。每次打完仗,林彪就亲自往上面添加数字,并为之沾沾自喜…令人感觉...

1899

扫码关注云+社区