Example: Accessing Oracle NoSQL Database Using Spring Data Framework

The following example demonstrates how to access Oracle NoSQL Database from Spring using Oracle NoSQL Database SDK for Spring Data. In this example, using the Spring Data Framework, you set up a connection with Oracle NoSQL Database non-secure store, insert a row in the Student table, and then retrieve the data from the Student table.

In this example, you set up a Maven Project and then add the following classes/interfaces:
  • Student class
  • StudentRepository interface
  • AppConfig class
  • App class

After that, you will run the Spring application to get the desired output. The following steps discuss this in detail.

  1. Set up a Maven project with the following POM file dependencies.

    <dependencies>
        <dependency>
            <groupId>com.oracle.nosql.sdk</groupId>
            <artifactId>spring-data-oracle-nosql</artifactId>
        </dependency>
    </dependencies>
  2. Create a new package and add the following Student entity class to persist. This entity class represents a table in the Oracle NoSQL Database and an instance of this entity corresponds to a row in that table.

    import com.oracle.nosql.spring.data.core.mapping.NosqlId;
    import com.oracle.nosql.spring.data.core.mapping.NosqlTable;
     
    /*The @NosqlTable annotation specifies that
      this class will be mapped to an Oracle NoSQL Database table.*/
    @NosqlTable
    public class Student {
        /*The @NosqlId annotation specifies that this field will act 
          as the ID field. And the generated=true attribute specifies 
          that this ID will be auto-generated by a sequence.*/
        @NosqlId(generated = true)
        long id;
        String firstName;
        String lastName;
        /* public or package protected constructor required when retrieving from database */
        public Student() {  
        } 
        /*This method overrides the toString() method, and then 
          concatenates id, firstname, and lastname, and then returns a String*/
        @Override
        public String toString() {
            return "Student{" +
                "id=" + id + ", " +
                "firstName=" + firstName + ", " +
                "lastName=" + lastName +
                '}';
        }
    }
  3. Create the following StudentRepository interface. This interface must extend the NosqlRepository interface and provide the entity class and the data type of the primary key in that class as sub-typing to the NosqlRepository interface. This NosqlRepository interface provides methods that could be used to retrieve data from the database.

    import com.oracle.nosql.spring.data.repository.NosqlRepository;
     
    /*The Student is the entity class, and Long is the data type of the
      primary key in the Student class. This interface implements a derived query 
      findByLastName and returns an iterable instance of the Student class.*/
    public interface StudentRepository extends NosqlRepository<Student, Long> {
        /*The Student table is searched by lastname and 
          returns an iterable instance of the Student class.*/
        Iterable<Student> findByLastName(String lastname);
    }
  4. Create the following AppConfig class that extends AbstractNosqlConfiguration class to provide the connection details of the database.

    import oracle.nosql.driver.kv.StoreAccessTokenProvider;
     
    import com.oracle.nosql.spring.data.config.AbstractNosqlConfiguration;
    import com.oracle.nosql.spring.data.config.NosqlDbConfig;
    import com.oracle.nosql.spring.data.repository.config.EnableNosqlRepositories;
     
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
     
    /*The @Configuration annotation specifies that this class can be 
      used by the Spring Data Framework as a source of bean definitions.*/
    @Configuration
    //annotation to enable NoSQL repositories.
    @EnableNosqlRepositories
    public class AppConfig extends AbstractNosqlConfiguration {
     
        public static NosqlDbConfig nosqlDBConfig =
            new NosqlDbConfig("hostname:port", new StoreAccessTokenProvider());
     
    /*The @Bean annotation tells the Spring Data Framework that the returned object 
      should be registered as a bean in the Spring application.*/
    @Bean
        public NosqlDbConfig nosqlDbConfig() {
            return nosqlDBConfig;
        }
    }

    Note:

    See Setting up the Connection section to know more about connecting to an Oracle NoSQL Database secure store.
  5. This example uses the CommandLineRunner interface to create a runner class that implements the run method and has the main method. You can code the functionality as per your requirements by implementing any of the various interfaces that the Spring Data Framework provides. For more information on setting up a Spring boot application, see Spring Boot.

    In the following code, the first two Student entities are created and saved. You then search for all the rows in the Student table and print the results to the output.

    import com.oracle.nosql.spring.data.core.NosqlTemplate;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.ConfigurableApplicationContext;
    
    /*The @SpringBootApplication annotation helps you to build 
      an application using Spring Data Framework rapidly.*/
    @SpringBootApplication
    public class App implements CommandLineRunner {
    
        /*The annotation enables Spring Data Framework to look up the 
          configuration file for a matching bean.*/
        @Autowired
        private StudentRepository repo;
    
        public static void main( String[] args ) {
            ConfigurableApplicationContext ctx = 
                SpringApplication.run(App.class, args);
            SpringApplication.exit(ctx, () -> 0);
            ctx.close();
            System.exit(0);
        }
    
        @Override
        public void run(String... args) throws Exception {
    
            System.out.println("=== Start of App ====");
    
            //Delete all the existing rows of data, if any, in the Student table.
            repo.deleteAll();
    
            //Create a new Student instance and load values into it.
            Student s1 = new Student();
            s1.firstName = "John";
            s1.lastName = "Doe";
    
            //Save the Student instance.
            repo.save(s1);
    
            //Create a new Student instance and load values into it.
            Student s2 = new Student();
            s2.firstName = "John";
            s2.lastName = "Smith";
     
            //Save the Student instance.
            repo.save(s2);
    
    
            System.out.println("\nfindAll:");
            /*Selects all the rows in the Student table 
              and load it into an iterable instance.*/
            Iterable<Student> students = repo.findAll();
    
            //Print the values to the output from the iterable object.
            for (Student s : students) {
                System.out.println("  Student: " + s);
            }
    
            System.out.println("\nfindByLastName: Smith");
            /*The Student table is searched by lastname  
              and an iterable instance of the Student class is returned.*/
            students = repo.findByLastName("Smith");
    
            //Print the values to the output from the iterable instance.
            for (Student s : students) {
                System.out.println("  Student: " + s);
            }
    
            System.out.println("=== End of App ====");
        }
    }
  6. Run the program from the runner class. You will get the following output.
    === Start of App ====
    findAll:
      Student: Student{id=5, firstName=John, lastName=Doe}
      Student: Student{id=6, firstName=John, lastName=Smith}
     
    findByLastName: Smith
      Student: Student{id=6, firstName=John, lastName=Smith}
    === End of App ====