การใช้งาน PostgreSQL กับ Spring Boot / Node.js / Golang

Sharing is caring!

PostgreSQL เป็นฐานข้อมูลโอเพนซอร์สที่ทรงพลัง และนิยมใช้งานร่วมกับหลายภาษา ไม่ว่าจะเป็น Spring Boot (Java), Node.js, หรือ Golang บทความนี้จะอธิบายการเชื่อมต่อ การตั้งค่า และตัวอย่าง CRUD พื้นฐานในแต่ละภาษา

1. PostgreSQL + Spring Boot

Spring Boot เป็น Framework ของ Java ที่ช่วยพัฒนา REST API ได้รวดเร็ว โดยสามารถเชื่อมต่อกับ PostgreSQL ผ่าน JPA/Hibernate

การตั้งค่า application.yml

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: postgres
    password: secret
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.PostgreSQLDialect
  

ตัวอย่าง Entity + Repository

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}
  

ตัวอย่าง Controller

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository repo;

    @GetMapping
    public List<User> all() {
        return repo.findAll();
    }

    @PostMapping
    public User create(@RequestBody User user) {
        return repo.save(user);
    }
}
  

2. PostgreSQL + Node.js

Node.js สามารถเชื่อม PostgreSQL ผ่าน Library pg เหมาะกับงาน Web API หรือ Realtime Application

การติดตั้ง

npm install pg express
  

ตัวอย่างการเชื่อมต่อ

const { Pool } = require('pg');
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'mydb',
  password: 'secret',
  port: 5432,
});

module.exports = pool;
  

ตัวอย่าง API CRUD

const express = require('express');
const pool = require('./db');
const app = express();
app.use(express.json());

app.get('/users', async (req, res) => {
  const result = await pool.query('SELECT * FROM users');
  res.json(result.rows);
});

app.post('/users', async (req, res) => {
  const { name, email } = req.body;
  const result = await pool.query(
    'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *',
    [name, email]
  );
  res.json(result.rows[0]);
});

app.listen(3000, () => console.log('Server running on port 3000'));

3. PostgreSQL + Golang

Golang สามารถเชื่อมต่อ PostgreSQL ผ่าน Driver pq และใช้ Library gorm สำหรับ ORM

การติดตั้ง

go get github.com/lib/pq
go get gorm.io/gorm
go get gorm.io/driver/postgres
  

ตัวอย่างการเชื่อมต่อ

package main

import (
  "gorm.io/driver/postgres"
  "gorm.io/gorm"
)

type User struct {
  ID    uint   `gorm:"primaryKey"`
  Name  string
  Email string
}

func main() {
  dsn := "host=localhost user=postgres password=secret dbname=mydb port=5432 sslmode=disable"
  db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
  if err != nil {
    panic("failed to connect database")
  }

  db.AutoMigrate(&User{})

  db.Create(&User{Name: "Alice", Email: "[email protected]"})
}
  

4. การเปรียบเทียบ

ภาษาLibrary / Frameworkความเหมาะสม
Spring Boot (Java)Spring Data JPA, Hibernateระบบ Enterprise, Transaction เยอะ
Node.jspg, expressWeb API, Realtime, Startup
Golangpq, gormระบบที่เน้น Performance, Microservices

Best Practices

  • ใช้ Connection Pooling เช่น HikariCP, pg-pool, Gorm Connection Pool
  • ใช้ Migration Tool เช่น Flyway, Liquibase, golang-migrate
  • เขียน Query ให้มี Index รองรับ
  • ทำ Monitoring ด้วย pg_stat_statements, Prometheus, Grafana

สรุป

PostgreSQL สามารถใช้งานร่วมกับหลายภาษาได้อย่างยืดหยุ่น ทั้ง Spring Boot, Node.js, และ Golang แต่ละภาษามี Library และ Framework ที่ช่วยให้การเชื่อมต่อและจัดการข้อมูลง่ายขึ้น การเลือกใช้งานขึ้นอยู่กับลักษณะของระบบ เช่น Enterprise, Web API, หรือ Microservices

SEO Keywords

PostgreSQL Spring Boot,Postgres Node.js Example,Postgres Golang Gorm,Postgres CRUD API,PostgreSQL with Java,PostgreSQL with JavaScript,PostgreSQL with Go

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *