文档章节

Spring boot with PostgreSQL

netkiller-
 netkiller-
发布于 2017/04/27 13:44
字数 704
阅读 164
收藏 0

Spring boot with PostgreSQL

Original 2017-04-27 景峯 Netkiller

本文节选自《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

 

Donations (打赏)

We accept PayPal through:

https://www.paypal.me/netkiller

Wechat (微信) / Alipay (支付宝) 打赏:

http://www.netkiller.cn/home/donations.html

 

 

作者相关文章:

Struts2 S2-046, S2-045 Firewall(漏洞防火墙)

应用程序的通信成本

攻城狮的自我营销

压力测试中存在的问题

数据库与图片完美解决方案

数据库进程间通信解决方案

数据库进程间通信解决方案之MQ

Linux 系统安全与优化配置

Tomcat 安全配置与性能优化

PHP 安全与性能

Linux 系统与数据库安全

运维必备技能 WEB 日志分析

Spring data mongodb @Document定义Enum/List/Map数据结构

 

转载请注明出处与作者声明,扫描二维码关注作者公众好,不定期更新文章

© 著作权归作者所有

共有 人打赏支持
netkiller-

netkiller-

粉丝 694
博文 264
码字总数 368425
作品 10
深圳
部门经理
私信 提问
云栖社区2019年1月技术活动:PG, Java,Spark等30+场预告【持续更新】

应广大开发者的需求,云栖社区将技术活动,如技术直播、系列公开课、Meetup、峰会、钉群分享等进行了预告与整理。欢迎大家分享给小伙伴们!如有建议,欢迎联系我们,联系方式见下方二维码。 ...

技术小能手
2018/12/25
0
0
聊聊servicecomb-saga的alpha-server

序 本文主要研究一下servicecomb-saga的alpha-server 启动alpha-server alpha-server是servicecomb-saga的分布式事务协调中心,采用spring boot开发,可以直接从jar包启动,需要依赖mysql或p...

go4it
2018/07/29
0
0
mybatis spring boot starter配置

maven application.yml配置 配置项mybatis-spring-boot-autoconfigure-1.2.1-sources.jar!/org/mybatis/spring/boot/autoconfigure/MybatisProperties.java configLocation 指定mybatis-con......

go4it
2017/05/15
0
0
面向 Java 开发者的 NoSQL 选项

Java 社区为我所了解和热爱,所以即使 NoSQL 数据库很少被捆绑到一种语言,我还是为全世界的 Java 开发者写下这篇文章。在这篇文章中,我将向你展示 NoSQL 数据库的几种选择。在探讨所有的选...

oschina
2017/10/09
2.1K
2
Spring jdbcTeamplate调用postpresql的存储过程

postgresql的函数和存储过程都集合起来了,那如何在spring jdbcTeamplate调用postgresql的函数像其他数据库一样,使用“call”的这种方式呢? ----------- 补充 --------------------- 我现在...

SeizeMissing
2018/01/08
254
2

没有更多内容

加载失败,请刷新页面

加载更多

https

进入阿里云域名后台,修改DNS为阿里云官方DNS(默认为官方),然后点击“免费开启SSL证书” 点击“申请”、“验证”并等待签发 然后根据自己的服务器类型下载对应的证书 我使用的是lnmpa工具...

临江仙卜算子
11分钟前
0
0
Quartz监听器Listerner

概述 Quartz的监听器用于当任务调度中你所关注事件发生时,能够及时获取这一事件的通知。Quartz监听器主要有JobListener、TriggerListener、SchedulerListener三种,顾名思义,分别表示任务、...

大笨象会跳舞吧
38分钟前
3
0
Call exception, tries=10, retries=35, started=38348 ms ago, cancelled=false, msg=pc-node1 row

写hbase的问题,2019-01-18 23:23:28,082 | INFO | [hconnection-0x6431d54d-shared--pool2-t5] | Call exception, tries=10, retries=35, started=38348 ms ago, cancelled=false, msg=p......

stys35
41分钟前
2
0
docker 安装portainer、gogs、redis、mongodb、es、rabbitmq、mysql、jenkins、harbor

1、准备三台虚拟机ip如下 编号 Ip 1 192.168.100.101 2 192.168.100.102 3 192.168.100.103 2、镜像应用编排 192.168.100.101 主要安装系统运维相关服务 192.168.100.102 主要安装mysql、mon...

北岩
51分钟前
7
0
storm 提交任务报SocketException错误及解决办法

提交任务爆错: org.apache.storm.thrift.transport.TTransportException: java.net.SocketException: Broken pipe (Write failed) ..... Caused by: org.apache.storm.thrift.transport.TTr......

jingshishengxu
55分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部