文档章节

Spring boot with PostgreSQL

netkiller-
 netkiller-
发布于 2017/04/27 13:44
字数 704
阅读 133
收藏 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-

粉丝 686
博文 255
码字总数 346643
作品 10
深圳
部门经理
私信 提问
聊聊servicecomb-saga的alpha-server

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

go4it
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
[笔记]将系统的数据库从MySQL 5.5迁移到PostgreSQL 9.1

环境 Windows Server 2003 x64 简体中文, MySQL 5.5 (UTF8编码), PostgreSQL 9.1.4-1 (UTF8编码) Spring 3.0.7, Struts 2.3.4, Hibernate 3.5.5 从MySQL迁移到PostgreSQL ------------------......

leeoo
2012/07/22
0
3
MyBatis 简化开发框架 - fastmybatis

fastmybatis是一个mybatis开发框架,目的为简化mybatis的开发,让开发更高效。 零配置快速上手 无需编写xml文件即可完成CRUD操作 支持mysql,sqlserver,oracle,postgresql,sqlite 支持自定...

tanghc
06/20
0
0
Spring Cloud Data Flow 1.6.0 RC1 发布

Spring Cloud Data Flow 1.6 RC1 发布了,Spring Cloud Data Flow 是构建数据集成和实时数据处理流水线的工具包。 此版本主要更新内容有以下几个方面: PCF Scheduler:Pivotal Cloud Found...

h4cd
07/24
0
0

没有更多内容

加载失败,请刷新页面

加载更多

结合lucene谈谈日期的压缩问题

说起日期值的压缩,一般容易想到的办法是将日期转化成long类型,然后再通过变长整形进行压缩,我算了一下按照毫秒来算最多占用5个字节(可以通过“谈谈变长整型”中的表查看),确实节省了部...

FAT_mt
42分钟前
0
0
导出私有函数与私有变量

在Go语言中, package中包含函数与变量通过identifier的首字母是否大写来决定它是否可以被其它package所访问。当一个函数或变量名称为小写字母时,默认是无法被其他package引用的. 有没有办法...

xtof
43分钟前
0
0
new Date() 在Safari下的 Invalid Date问题

问题复现 var timeStr = '2018-11-11 00:00:00';var time = new Date(timeStr);// error: Invalid Date... 在safari浏览器下,time为Invalid Date, 导致后面代码执行错误; 其他浏览器诸...

会写代码的husky
47分钟前
2
0
0009-如何升级Cloudera Manager和CDH

1.文档编写目的 本文档讲述如何升级Cloudera Manager和CDH,通过本文档,您将学习到以下知识: 1.如何对Cloudera Manager进行停机升级 2.如何对CDH进行停机升级 3.如何在不影响集群作业的情况...

Hadoop实操
57分钟前
1
0
vue2中引用 better-scroll的方法

文章主要介绍了vue2中引用better-scroll和使用 better-scroll的方法,使用时有三个要点及注意事项在文中给大家详细介绍 ,需要的朋友可以参考下 使用时有三个要点: 一:html部分 <div class...

前端攻城老湿
今天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部