PlusMagi's Blog By Pitt Phunsanit

Spring 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 และข้อมูล


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

Exit mobile version