In this tutorial, we are going to look at Scala using Spring MVC and MongoDB.

The first step is a Maven project and adds the following content to your Maven POM file. The easiest way to bootstrap a Spring Boot Maven project is by using Spring Initializer.

The next step is to set the Scala dependency in the pom.xml:

 <dependencies>

        ...
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.13.3</version>
        </dependency>
    </dependencies>
     <build>
        <finalName>spring-scala-mongodb</finalName>
        <plugins>
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>4.4.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

If you want to run MongoDB locally, a good option might be Docker, which you can run with the command below:

docker run -d --name mongodb-instance -p 27017:27017 mongo

In this project, we’ll create a sample that will handle a user in its respective client. The first step is to create the entity class, in this sample, a User class.

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import scala.annotation.meta.field
import scala.beans.BeanProperty
@Document class User
(@(Id@field) @BeanProperty var id: String,
 @BeanProperty var name: String,
 @BeanProperty var country: String) {
  def this() = this(null, null, null)
}

The repository interface makes the integration between the Scala application and the MongoDB instance easy:

import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
@Repository trait UserRepository extends CrudRepository[User, String]

#java #spring #scala #cloud (add topic) #platform.sh #cloud

Hello World Scala in the Cloud With Spring
1.45 GEEK