springboot+jpa connects to SQLServer database

1. Introduce the jar package required to connect to SQL Server

<!--sqlServer-->
<dependency>
	<groupId>com.microsoft.sqlserver</groupId>
	<artifactId>sqljdbc4</artifactId>
	<version>4.0</version>
</dependency>

1. If the remote warehouse cannot download the jar package, it is recommended to manually download sqljdbc4.jar and import it into the local warehouse.
sqljdbc4.jar download address:
Link: https://pan.baidu.com/s/1Jh9Vu6LX06qXL8pKZWwyoA
Extraction code: ffkk
2. Add to local warehouse
In the folder where the jar package is located, open cmd and execute the command:

mvn install:install-file -Dfile=sqljdbc4.jar -Dpackaging=jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0

2. Properties configuration file

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=数据库名
spring.datasource.username=sa
spring.datasource.password=*****

spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.default_schema=dbo
spring.jpa.database=sql_server
spring.jpa.database-platform=com.sq.fms.config.SqlServerDialect  # 自定义的方言类

Dialect class: The SQL Server database version I use is 2019, so I configured the dialect class myself.

package com.sq.fms.config;

import org.hibernate.dialect.SQLServer2012Dialect;
import org.hibernate.type.StandardBasicTypes;
import java.sql.Types;

/**
 * 自定义方言类,处理使用原生Sql查询,数据类型和hibernate对应关系

 继承SQLServer2012Dialect,如果sqlServer版本是2008则继承
 	 SQLServer2008Dialect,其他版本继承各自的版本
 
 */
public class SqlServerDialect extends SQLServer2012Dialect {
    
    

    /**
     * 设置sql server 数据库方言转换
     */
    public SqlServerDialect() {
    
    
        registerHibernateType(Types.NCHAR, StandardBasicTypes.CHARACTER.getName());
        registerHibernateType(Types.NCHAR, 1, StandardBasicTypes.CHARACTER.getName());
        registerHibernateType(Types.NCHAR, 255, StandardBasicTypes.STRING.getName());
        registerHibernateType(Types.NVARCHAR, StandardBasicTypes.STRING.getName());
        registerHibernateType(Types.LONGNVARCHAR, StandardBasicTypes.TEXT.getName());
        registerHibernateType(Types.NCLOB, StandardBasicTypes.CLOB.getName());
    }
}

Supplement: SQLServer sets sa user login: https://blog.csdn.net/qq_42182034/article/details/109066268

Guess you like

Origin blog.csdn.net/qq_42182034/article/details/108700823