例: Spring Data Frameworkを使用したOracle NoSQL Databaseへのアクセス

次の例は、Oracle NoSQL Database SDK for Spring Dataを使用して、SpringからOracle NoSQL Databaseにアクセスする方法を示しています。この例では、Spring Data Frameworkを使用して、Oracle NoSQL Databaseの非セキュアなストアとの接続を設定し、Student表に行を挿入してから、Student表からデータを取得します。

この例では、Mavenプロジェクトを設定してから、次のクラス/インタフェースを追加します。
  • Studentクラス
  • StudentRepositoryインタフェース
  • AppConfigクラス
  • Appクラス

その後、Springアプリケーションを実行して目的の出力を取得します。次のステップでは、これについて詳しく説明します。

  1. 次のPOMファイルの依存性を使用して、Mavenプロジェクトを設定します。

    <dependencies>
        <dependency>
            <groupId>com.oracle.nosql.sdk</groupId>
            <artifactId>spring-data-oracle-nosql</artifactId>
        </dependency>
    </dependencies>
  2. 新しいパッケージを作成し、次のStudentエンティティ・クラスを追加して永続させます。このエンティティ・クラスはOracle NoSQL Databaseの表を表しています。また、このエンティティのインスタンスはその表の行に対応します。

    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. 次のStudentRepositoryインタフェースを作成します。このインタフェースは、NosqlRepositoryインタフェースを拡張して、そのクラスの主キーのエンティティ・クラスとデータ型をサブタイプとしてNosqlRepositoryインタフェースに提供する必要があります。このNosqlRepositoryインタフェースは、データベースからデータを取得するために使用できるメソッドを備えています。

    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. 次のAppConfigクラスを作成します。これは、データベースの接続詳細を指定するために、AbstractNosqlConfigurationクラスを拡張するものです。

    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;
        }
    }

    ノート:

    Oracle NoSQL Databaseセキュア・ストアへの接続の詳細は、「接続の設定」の項を参照してください。
  5. この例では、CommandLineRunnerインタフェースを使用して、runメソッドとmainメソッドを実装するランナー・クラスを作成します。Spring Data Frameworkが提供する各種インタフェースのいずれかを実装することで、目的の要件に応じた機能をコーディングできます。Spring bootアプリケーションの設定の詳細は、「Spring Boot」を参照してください。

    次のコードでは、最初の2つのStudentエンティティを作成してから保存します。その次に、Student表のすべての行を検索して、結果を出力します。

    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. ランナー・クラスからプログラムを実行します。次の出力が表示されます。
    === 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 ====