例: 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
表からデータを取得します。
Student
クラスStudentRepository
インタフェースAppConfig
クラスApp
クラス
その後、Springアプリケーションを実行して目的の出力を取得します。次のステップでは、これについて詳しく説明します。
-
次のPOMファイルの依存性を使用して、Mavenプロジェクトを設定します。
<dependencies> <dependency> <groupId>com.oracle.nosql.sdk</groupId> <artifactId>spring-data-oracle-nosql</artifactId> </dependency> </dependencies>
-
新しいパッケージを作成し、次の
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 + '}'; } }
-
次の
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); }
-
次の
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; } }
-
この例では、
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 ===="); } }
- ランナー・クラスからプログラムを実行します。次の出力が表示されます。
=== 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 ====