Connect to MSSQL Server in JPA

In the examples of Huong Dan Java on JPA, I often use MySQL as an example because it is free and easy to use, mainly because I’m familiar with it: D. I think some of you, especially the students, often use MSSQL Server. So, I write this tutorial to guide you all how to connect MSSQL Server in JPA.

First, I will create a Maven project as an example:

Connect to MSSQL Server in JPA

Since I’m going to use JPA with Hibernate’s implementation, I’ll add Hibernate dependencies like this:

Project Lombok:

To use JPA with MSSQL Server, we need to add the JDBC Driver dependency for MSSQL Server as mssql-jdbc. You can find the latest version of mssql-jdbc from Microsoft on the Remote Maven Repository at https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc. This JDBC Driver is available in many versions for different versions of Java, please select the correct version of Java that you are using.

Here, I am using Java 8 so I will add the dependency of mssql-jdbc as follows:

In this example, I will define a simple table that contains class information:

Entity of this table:

The most important part is the configuration file for JPA’s persistence.xml configuration file. The contents of this file will be configured as follows:

Here, the MSSQL class driver will be com.microsoft.sqlserver.jdbc.SQLServerDriver and the url to connect to the database will look like jdbc:sqlserver://<ip>:<port>;databaseName=<database_name>. Inside:

  • ip is the address of MSSQL Server
  • The port is the port that MSSQL Server runs on this server. The default port of MSSQL is 1443. If you change the port then correct it.
  • database_name is the name of the database that we need to work on.

OK, everything needs to be done, now try running a small example:

Result:

Connect to MSSQL Server in JPA

Add Comment