วัน: 11 พฤษภาคม 2024

Spring Boot: connection SQL ServerSpring Boot: connection SQL Server

สำหรับการเชื่อมต่อ Java Spring Boot เข้ากับ SQL Server อย่างที่เคยตั้งค่าไว้ใน Docker Compose นั้น มีขั้นตอนสำคัญอยู่ที่การตั้งค่า pom.xml และ application.properties ( หรือ yml ) ดังนี้ครับ


เพิ่ม Dependency ใน pom.xml

คุณต้องใช้ Driver สำหรับ MSSQL และ Spring Data JPA เพื่อจัดการกับฐานข้อมูล

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

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

ตั้งค่า application.properties

เนื่องจากคุณใช้ SQL Server 2025 และมีการตั้งค่า healthcheck ที่ใช้ encrypt ( ผ่าน flag -C ในคำสั่ง sqlcmd ) ตัว Connection String ใน Java ควรระบุให้ชัดเจนเพื่อป้องกันปัญหาเรื่อง SSL/TLS

# Connection String
# หากรัน App นอก Docker ให้ใช้ localhost แต่ถ้ารันใน Docker network เดียวกันให้ใช้ชื่อ service (db-sqlserver)
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=master;encrypt=true;trustServerCertificate=true;

spring.datasource.username=sa
spring.datasource.password=4w2e36jqg6mG
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

# JPA / Hibernate Config
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
# ระบุ Dialect สำหรับ SQL Server
spring.jpa.database-platform=org.hibernate.dialect.SQLServerDialect

ข้อควรระวังเรื่อง Collation และข้อมูล

  • Thai Collation: คุณตั้งค่า Thai_100_CI_AS ไว้ใน Docker ซึ่งดีมากสำหรับการเรียงลำดับภาษาไทย ( ก-ฮ ) แต่อย่าลืมว่าใน Spring Boot Entity หากต้องการเก็บข้อความภาษาไทย ควรใช้ Type เป็น NVARCHAR ในฐานข้อมูล ( Hibernate จะจัดการให้เองถ้าใช้ @Column(columnDefinition = "nvarchar(255)" ) หรือตั้งค่า Dialect ให้ถูกต้อง )
  • Volume Mapping: จากไฟล์ Compose ที่ทำ ./data:/var/opt/mssql ไว้ ข้อมูลจะถูกเก็บในเครื่องคุณที่โฟลเดอร์ data แม้จะลบคอนเทนเนอร์ออก ข้อมูลก็จะไม่หายครับ
  • Encryption: ใน Driver เวอร์ชันใหม่ ๆ จะบังคับ encrypt=true เป็นค่าเริ่มต้น หากไม่ได้ลง Certificate จริงไว้ที่ Server ต้องใส่ ;trustServerCertificate=true ต่อท้าย URL เสมอ มิฉะนั้น Spring Boot จะเชื่อมต่อไม่สำเร็จ

อ่านเพิ่มเติม