{"id":3390,"date":"2017-02-14T11:14:48","date_gmt":"2017-02-14T16:14:48","guid":{"rendered":"http:\/\/springframework.guru\/?p=3390"},"modified":"2024-10-21T10:23:13","modified_gmt":"2024-10-21T14:23:13","slug":"configuring-spring-boot-for-microsoft-sql-server","status":"publish","type":"post","link":"https:\/\/springframework.guru\/configuring-spring-boot-for-microsoft-sql-server\/","title":{"rendered":"Configuring Spring Boot for Microsoft SQL Server"},"content":{"rendered":"<p>Out of the box, Spring Boot is very easy to use with the <a href=\"http:\/\/www.h2database.com\/html\/main.html\" target=\"_blank\" rel=\"noopener noreferrer\">H2 Database<\/a>. Spring programmers typically prefer writing code against such lightweight in-memory database, rather than on an enterprise database server such as Microsoft SQL Server or Oracle.<\/p>\n<p>In-memory databases come with several restrictions making them useful only in the development stages in local environments. While in-memory databases are great to develop against, data is not persisted to disk, thus is lost when the database is shut down.<\/p>\n<p>As the development progresses, you would most probably require an RDBMS to develop and test your application before deploying it to use a production database server. I have written a series of posts on integrating Spring Boot for <a href=\"http:\/\/springframework.guru\/configuring-spring-boot-for-oracle\/\" target=\"_blank\" rel=\"noopener noreferrer\">Oracle<\/a>, <a href=\"http:\/\/springframework.guru\/configuring-spring-boot-for-mysql\/\" target=\"_blank\" rel=\"noopener noreferrer\">MySQL<\/a>, <a href=\"http:\/\/springframework.guru\/configuring-spring-boot-for-mariadb\/\" target=\"_blank\" rel=\"noopener noreferrer\">MariaDB<\/a>, and <a href=\"http:\/\/springframework.guru\/configuring-spring-boot-for-postgresql\/\" target=\"_blank\" rel=\"noopener noreferrer\">PostgreSQL<\/a>.<\/p>\n<p>Spring makes switching between RDBM&#8217;s simple. When you\u2019re using <a href=\"http:\/\/projects.spring.io\/spring-data-jpa\/\" target=\"_blank\" rel=\"noopener noreferrer\">Spring Data JPA<\/a> with an ORM technology such as\u00a0<a href=\"http:\/\/hibernate.org\/\" target=\"_blank\" rel=\"noopener noreferrer\">Hibernate<\/a>, the persistence layer is nicely well decoupled. Which allows you to run your code against multiple databases. The level of decoupling even allows you to easily switch between an RDBMS and a <a href=\"https:\/\/www.mongodb.com\/nosql-explained\" target=\"_blank\" rel=\"noopener noreferrer\">NoSQL database<\/a>, such as <a href=\"https:\/\/www.mongodb.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">MongoDB<\/a>.<\/p>\n<p>In this post, I will discuss Spring Boot configuration for <a href=\"https:\/\/www.microsoft.com\/en-in\/sql-server\/sql-server-2016\" target=\"_blank\" rel=\"noopener noreferrer\">Microsoft SQL Server<\/a>.<\/p>\n<h2>SQL Server Configuration<\/h2>\n<p>For this post, I\u2019m using <a href=\"https:\/\/www.microsoft.com\/en-in\/download\/details.aspx?id=42299\" target=\"_blank\" rel=\"noopener noreferrer\">SQL Server 2014 Express<\/a> installed locally on my laptop. I used <a href=\"http:\/\/download.microsoft.com\/download\/1\/5\/6\/156992E6-F7C7-4E55-833D-249BD2348138\/ENU\/x86\/SQLManagementStudio_x86_ENU.exe\" target=\"_blank\" rel=\"noopener noreferrer\">SQL Server 2014 Management Studio<\/a> to connect to the database server using SQL Server Authentication.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Connect_To_Sql_Server.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-3391\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Connect_To_Sql_Server.png\" alt=\"Connect To SQL Server\" width=\"412\" height=\"310\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Connect_To_Sql_Server.png 412w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Connect_To_Sql_Server-300x226.png 300w\" sizes=\"(max-width: 412px) 100vw, 412px\" \/><\/a><br \/>\nOnce you are logged in, create a <strong>springbootdb<\/strong> database from the <strong>Object Explorer<\/strong> window.<br \/>\n<a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Sql_Server_Management_Studio.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3392 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Sql_Server_Management_Studio.png\" alt=\"Configure SQL Server database for use with Spring Boot\" width=\"787\" height=\"451\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Sql_Server_Management_Studio.png 787w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Sql_Server_Management_Studio-300x172.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/Sql_Server_Management_Studio-768x440.png 768w\" sizes=\"(max-width: 787px) 100vw, 787px\" \/><\/a><\/p>\n<p>A common problem that trips up many Java developers trying to connect to SQL Server is this error:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">com.microsoft.sqlserver.jdbc.SQLServerException: The TCP\/IP connection to the host localhost, port 1433 has failed. Error: \u201cConnection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP\/IP connections at the port, and that no firewall is blocking TCP connections to the port.\u201d.<\/pre>\n<p>I too learned the hard way to resolve it with these steps.<\/p>\n<ol>\n<li style=\"list-style-type: none;\">\n<ol>\n<li>From the <strong>Start<\/strong> menu, open <strong>SQL Server 2014 Configuration Manager<\/strong>.<\/li>\n<li>Click <strong>Protocol for SQLEXPRESS<\/strong> under <strong>SQL Server Network Configuration<\/strong> on the left pane. On the right pane, right- click <strong>TCP\/IP<\/strong>, and select <strong>Properties<\/strong>.<\/li>\n<li>On the <strong>TCP\/IP Properties<\/strong> dialog box that appears, click the <strong>IP Addresses<\/strong> tab.<\/li>\n<li>Scroll down to locate the <strong>IPALL<\/strong> node. Remove any value, if present for <strong>TCP Dynamic Ports<\/strong> and specify <strong>1433<\/strong> for <strong>TCP Port<\/strong>.<\/li>\n<\/ol>\n<\/li>\n<\/ol>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/TCPIP_Propertie.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3393 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/TCPIP_Propertie.png\" alt=\"TCP\/IP Properties for SQL Server\" width=\"412\" height=\"473\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/TCPIP_Propertie.png 412w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/TCPIP_Propertie-261x300.png 261w\" sizes=\"(max-width: 412px) 100vw, 412px\" \/><\/a><\/p>\n<ol>\n<li>Click <strong>OK<\/strong>.<\/li>\n<li>Again right-click <strong>TCP\/IP<\/strong> on the right pane, and select <strong>Enable<\/strong>.<\/li>\n<li>On the <strong>SQL Server Services<\/strong> node, right-click <strong>SQL Server (SQLEXPRESS)<\/strong>, and select <strong>Restart<\/strong>.<\/li>\n<\/ol>\n<p>This sets up SQL Server to be reached from JDBC code.<\/p>\n<h2>SQL Server Dependencies<\/h2>\n<p>To connect with SQL Server from Java applications, Microsoft provides a Microsoft JDBC Driver for SQL Server. However, till November 2016, Maven did not directly support the driver as it was not open sourced. By making it open source, Microsoft finally made the driver available on the Maven Central Repository. More information can be found <a href=\"https:\/\/blogs.msdn.microsoft.com\/jdbcteam\/2016\/11\/17\/open-source-jdbc-maven\/\" target=\"_blank\" rel=\"noopener noreferrer\">here<\/a>.<\/p>\n<p>The Maven POM file of my Spring Boot application that brings in the database driver is this.<\/p>\n<h4>pom.xml<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\"><!--?xml version=\"1.0\" encoding=\"UTF-8\"?-->\n\n    4.0.0\n    guru.springframework\n    blogposts\n    0.0.1-SNAPSHOT\n    jar\n    Blog Posts\n    Misc Blog Posts\n    \n        org.springframework.boot\n        spring-boot-starter-parent\n        1.4.4.RELEASE\n         <!-- lookup parent from repository -->\n    \n    \n        UTF-8\n        guru.springframework.blog.BlogPostsApplication\n        1.8\n    \n    \n        \n            org.springframework.boot\n            spring-boot-starter\n        \n        \n            org.springframework.boot\n            spring-boot-starter-data-jpa\n        \n        \n            com.microsoft.sqlserver\n            sqljdbc4\n            4.0\n        \n        \n            org.springframework.boot\n            spring-boot-starter-test\n            test\n        \n    \n    \n        \n            \n                org.springframework.boot\n                spring-boot-maven-plugin\n            \n        \n    \n\n<\/pre>\n<h2>Spring Boot Properties<\/h2>\n<p>We need to override the H2 database properties being set by default in Spring Boot. The nice part is, Spring Boot sets default database properties only when you don\u2019t. So, when we configure SQL Server for use, Spring Boot won\u2019t setup the H2 database anymore.<\/p>\n<p>The following data source configurations are required to configure SQL Server with Spring Boot.<\/p>\n<h4>application.properties<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">spring.datasource.url=jdbc:sqlserver:\/\/localhost;databaseName=springbootdb\nspring.datasource.username=sa\nspring.datasource.password=Projects@123\nspring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver\nspring.jpa.show-sql=true\nspring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect\nspring.jpa.hibernate.ddl-auto = create-drop<\/pre>\n<p>As we are using JPA, we need to configure Hibernate for SQL Server too. Line 7 tells Hibernate to recreate the database on startup. This is definitely not the behavior we want if this was actually a production database You can set this property to the following values: <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">none<\/code>, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">validate<\/code>, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">update<\/code>, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">create-drop<\/code>.<\/p>\n<p>For a production database, you probably want to use <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">validate<\/code>.<\/p>\n<figure id=\"attachment_4223\" aria-describedby=\"caption-attachment-4223\" style=\"width: 300px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/bit.ly\/2yhpu6x\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4223 size-medium\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02-300x156.png\" alt=\"Spring Framework 5\" width=\"300\" height=\"156\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02-300x156.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02.png 560w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><figcaption id=\"caption-attachment-4223\" class=\"wp-caption-text\">Become a Spring Framework 5 Guru!<\/figcaption><\/figure>\n<h2>JPA Entity<\/h2>\n<p>In our example application, we will perform CRUD operations on a user. For that, we will write a simple JPA entity, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">User<\/code> for our application. I have written a post to use <a href=\"http:\/\/springframework.guru\/spring-boot-web-application-part-3-spring-data-jpa\/\" target=\"_blank\" rel=\"noopener noreferrer\">Spring Data JPA in a Spring Boot Web application<\/a>, and so won\u2019t go into JPA here.<\/p>\n<h4>User.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.blog.domain;\n\nimport javax.persistence.*;\n\n@Entity\n@Table(name = \"user_tbl\")\npublic class User {\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private Integer id;\n    private String name;\n    private int age;\n    public User() {\n    }\n\n    public User(String name, int age) {\n        this.name = name;\n        this.age = age;\n    }\n\n    public Integer getId() {\n        return id;\n    }\n    public void setId(Integer id) {\n        this.id = id;\n    }\n\n    public String getName() {\n        return name;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n\n    public int getAge() {\n        return age;\n    }\n    public void setAge(int age) {\n        this.age = age;\n    }\n    @Override\n    public String toString() {\n        return \"User{\" +\n                \", name='\" + name + '\\'' +\n                \", Age=\" + age +\n                '}';\n    }\n}<\/pre>\n<h2>JPA Repository<\/h2>\n<p>Spring Data JPA CRUD Repository is a feature of Spring Data JPA that I extensively use. Using it, you can just define an interface that extends <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">CrudRepository<\/code> to manage entities for most common operations, such as saving an entity, updating it, deleting it, or finding it by id. Spring Data JPA uses generics and reflection to generate the concrete implementation of the interface we define.<\/p>\n<p>For our <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">User<\/code> domain class we can define a Spring Data JPA repository as follows.<\/p>\n<h4>UserRepository.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.blog.repositories;\n\nimport guru.springframework.blog.domain.User;\nimport org.springframework.data.repository.CrudRepository;\n\npublic interface UserRepository extends CrudRepository&lt;User, Integer&gt; {\n    User findByName(String name);\n}<\/pre>\n<p>That\u2019s all we need to setup in Spring Boot to use SQL Server.<\/p>\n<p>Let&#8217;s write some test code for this setup.<\/p>\n<h4>UserRepositoryTest.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.blog.repositories;\n\nimport guru.springframework.blog.domain.User;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport static org.junit.Assert.*;\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class UserRepositoryTest {\n    @Autowired\n    private UserRepository userRepository;\n    @Before\n    public void setUp() throws Exception {\n        User user1= new User(\"Alice\", 23);\n        User user2= new User(\"Bob\", 38);\n        \/\/save user, verify has ID value after save\n        assertNull(user1.getId());\n        assertNull(user2.getId());\/\/null before save\n        this.userRepository.save(user1);\n        this.userRepository.save(user2);\n        assertNotNull(user1.getId());\n        assertNotNull(user2.getId());\n    }\n\n    @Test\n    public void testFetchData(){\n        \/*Test data retrieval*\/\n        User userA = userRepository.findByName(\"Bob\");\n        assertNotNull(userA);\n        assertEquals(38, userA.getAge());\n        \/*Get all products, list should only have two*\/\n        Iterable users = userRepository.findAll();\n        int count = 0;\n        for(User p : users){\n            count++;\n        }\n        assertEquals(count, 2);\n    }\n}<\/pre>\n<p>For the test, I have used JUnit. To know more about JUnit, you can refer my series on <a href=\"http:\/\/springframework.guru\/unit-testing-junit-part-1\/\" target=\"_blank\" rel=\"noopener noreferrer\">JUnit Testing<\/a>.<\/p>\n<p>The result of the JUnit test is this.<\/p>\n<p><a href=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/JUnit_Test_Result-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-3376 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/JUnit_Test_Result-1.png\" alt=\"JUnit Test Result for SQL Server\" width=\"965\" height=\"218\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/JUnit_Test_Result-1.png 965w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/JUnit_Test_Result-1-300x68.png 300w, https:\/\/springframework.guru\/wp-content\/uploads\/2017\/02\/JUnit_Test_Result-1-768x173.png 768w\" sizes=\"(max-width: 965px) 100vw, 965px\" \/><\/a><\/p>\n<h1>Conclusion<\/h1>\n<p>As you can see, it is very easy to configure Spring Boot for SQL Server. As usual, Spring Boot will auto configure sensible defaults for you. And as needed, you can override the default Spring Boot properties for your specific application.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Out of the box, Spring Boot is very easy to use with the H2 Database. Spring programmers typically prefer writing code against such lightweight in-memory database, rather than on an enterprise database server such as Microsoft SQL Server or Oracle. In-memory databases come with several restrictions making them useful only in the development stages in [&hellip;]<a href=\"https:\/\/springframework.guru\/configuring-spring-boot-for-microsoft-sql-server\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":4575,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[1],"tags":[177,178,29],"class_list":["post-3390","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-microsoft","tag-microsoft-sql-server","tag-spring-boot"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"jt","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/NewBannerBOOTSWeb.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-SG","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/3390"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=3390"}],"version-history":[{"count":8,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/3390\/revisions"}],"predecessor-version":[{"id":8298,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/3390\/revisions\/8298"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4575"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=3390"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=3390"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=3390"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}