RxJava2 与 JDBC 的集成,包括非阻塞连接池
ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[] :toc: :toc-placement!:
= rxjava2-jdbc
image:https://github.com/davidmoten/rxjava2-jdbc/actions/workflows/ci.yml/badge.svg["CI",link="https://github.com/davidmoten/rxjava2-jdbc/actions/workflows/ci.yml"] image:https://codecov.io/gh/davidmoten/rxjava2-jdbc/branch/master/graph/badge.svg["CodeCov",link="https://codecov.io/gh/davidmoten/rxjava2-jdbc"] image:https://maven-badges.herokuapp.com/maven-central/com.github.davidmoten/rxjava2-jdbc/badge.svg?style=flat[link="https://maven-badges.herokuapp.com/maven-central/com.github.davidmoten/rxjava2-jdbc"]
JDBC is so much simpler with rxjava2-jdbc.
For Rxjava 3.x see https://github.com/davidmoten/rxjava3-jdbc[rxjava3-jdbc].
Status: published to Maven Central
Maven site reports are https://davidmoten.github.io/rxjava2-jdbc/index.html[here] including https://davidmoten.github.io/rxjava2-jdbc/apidocs/index.html[javadoc].
toc::[]
== How to build
Use maven:
mvn clean installThe project builds fine on Java 8 to 17.
== Getting started Use this maven dependency:
com.github.davidmoten
rxjava2-jdbc
VERSION_HERE
If you want to use the built-in test database then add the Apache Derby dependency (otherwise you'll need the jdbc dependency for the database you want to connect to):
org.apache.derby
derby
10.14.2.0
== Database
To start things off you need a Database instance. Given the jdbc url of your database you can create a Database object like this:
Database db = Database.from(url, maxPoolSize);== Support for playing with rxjava2-jdbc!
If you want to have a play with a built-in test database then do this:
Database db = Database.test(maxPoolSize);To use the built-in test database you will need the Apache Derby dependency:
org.apache.derby
derby
10.14.2.0
The test database has a few tables (see link:rxjava2-jdbc/src/main/resources/database-test.sql[script]) including Person and Address with three rows in Person and two rows in Address:
Each time you call Database.test(maxPoolSize) you will have a fresh new database to play with that is loaded with data as described above.
== A query example
Let's use a Database instance to perform a select query on the Person table and write the names to the console:
Database db = Database.test();
db.select("select name from person")
.getAs(String.class)
.blockingForEach(System.out::println);Output is
FRED
JOSEPH
MARMADUKENote the use of blockingForEach. This is only for demonstration purposes. When a query is executed it is executed asynchronously on a scheduler that you can specify if desired. The default scheduler is:
Schedulers.from(Executors.newFixedThreadPool(maxPoolSize));While you are processing reactively you should avoid blocking calls but domain boundaries sometimes force this to happen (e.g. accumulate the results and return them as xml over the network from a web service call). Bear in mind also that if you are worried about the complexities of debugging RxJava programs then you might wish to make brief limited forays into reactive code. That's completely fine too. What you lose in efficiency you may gain in simplicity.
== Asynchrony
The query flowables returned by the Database all run asynchronously. This is required because of the use of non-blocking connection pools. When a connection is returned to the pool and then checked-out by another query that checkout must occur on a different thread so that stack overflow does not occur. See the > section for more details.
== Nulls
RxJava2 does not support streams of nulls. If you want to represent nulls in your stream then use java.util.Optional.
In the special case where a single nullable column is being returned and mapped to a class via getAs you should instead use getAsOptional:
Database.test()
.select("select date_of_birth from person where name='FRED'")
.getAsOptional(Instant.class)
.blockingForEach(System.out::println);Output:
Optional.emptyNulls will happily map to Tuples (see the next section) when you have two or more columns.
=== Null parameters You can specify an explicit null parameter like this:
Database.test()
.update("update person set date_of_birth = ?")
.parameter(null)
.counts()
.blockingForEach(System.out::println);or using named parameters:
Database.test()
.update("update person set date_of_birth = :dob")
.parameter(Parameter.create("dob", null))
.counts()
.blockingForEach(System.out::println);If you use a stream of parameters then you have to be more careful (nulls are not allowed in RxJava streams):\
Database.test()
.update("update person set date_of_birth = ?")
.parameterStream(Flowable.just(Parameter.NULL))
.counts()
.blockingForEach(System.out::println);== Tuple support
When you specify more types in the getAs method they are matched to the columns in the returned result set from the query and combined into a Tuple instance. Here's an example that returns Tuple2:
Database db = Database.test();
db.select("select name, score from person")
.getAs(String.class, Integer.class)
.blockingForEach(System.out::println);Output
Tuple2 [value1=FRED, value2=21]
Tuple2 [value1=JOSEPH, value2=34]
Tuple2 [value1=MARMADUKE, value2=25]Tuples are defined from Tuple2 to Tuple7 and for above that to TupleN.
== Manual mapping
You can map each row of the JDBC ResultSet to your own object using the get method:
Database db = Database.test();
db.select("select name, score from person order by name")
.get(rs -> new Person(rs.getString("name"), rs.getInt("score")))
.doOnNext(System.out::println) //
.subscribe();By the way it is definitely not a good idea to hang on to a bunch of rs objects as their state will always be that of the latest read row. For this reason you immediately map it to something else either by manually mapping or automapping.
== Automap
To map the result set values to an interface, first declare an interface:
interface Person {
@Column
String name();
@Column
int score();
}In the query use the autoMap method and let's use some of the built-in testing methods of RxJava2 to confirm we got what we expected:
Database db = Database.test();
db.select("select name, score from person order by name")
.autoMap(Person.class)
.doOnNext(System.out::println)
.firstOrError()
.map(Person::score)
.test()
.assertValue(21)
.assertComplete();If your interface method name does not exactly match the column name (underscores and case are ignored) then you can add more detail to the Column annotation:
interface Person {
@Column("name")
String fullName();
@Column("score")
int examScore();
}You can also refer to the 1-based position of the column in the result set instead of its name:
interface Person {
@Index(1)
String fullName();
@Index(2)
int examScore();
}In fact, you can mix use of named columns and indexed columns in automapped interfaces.
If you don't configure things correctly these exceptions may be emitted and include extra information in the error message about the affected automap interface:
AnnotationsNotFoundExceptionColumnIndexOutOfRangeExceptionColumnNotFoundExceptionClassCastExceptionAutomappedInterfaceInaccessibleException=== Automapped toString
The toString() method is implemented for automapped objects. For example the toString method for a Person object produces something like:
Person[name=FRED, score=21]=== Automapped equals/hashCode
The equals and hashCode methods on automapped objects have been implemented based on method value comparisons. For example
Person[name=FRED, score=21] is equal to Person[name=FRED, score=21]Person[name=FRED, score=21] is not equal to Person[name=FRED, score=22]Person[name=FRED, score=21] is not equal to Person2[name=FRED, score=21]Note that if you try to compare an automapped object with a custom implementation of the automapped interface then the custom implementation must implement equals/hashCode in the same way. In short, avoid doing that!
=== Automapped interface with default methods
=== Automap with annotated query
The automapped interface can be annotated with the select query:
@Query("select name, score from person order by name")
interface Person {
@Column
String name();
@Column
int score();
}To use the annotated interface:
Database
.test()
.select(Person.class)
.get()
.map(Person::name)
.blockingForEach(System.out::println);Output:
FRED
JOSEPH
MARMADUKEIn fact the .map is not required if you use a different overload of get:
Database
.test()
.select(Person.class)
.get(Person::name)
.blockingForEach(System.out::println);=== Automap with Kotlin See https://github.com/davidmoten/rxjava2-jdbc/blob/master/rxjava2-jdbc-kotlin-example/src/test/kotlin/RxJava2JdbcKotlinTest.kt[example]. Below is how you annotate an interface in Kotlin for automap:
@Query("select name from person order by name")
interface Person {
@Column("name")
fun nm() : String
}=== Auto mappings
The automatic mappings below of objects are used in the autoMap() method and for typed getAs() calls.
java.sql.Date,java.sql.Time,java.sql.Timestamp java.util.Datejava.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.lang.Longjava.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.time.Instantjava.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.time.ZonedDateTimejava.sql.Blob java.io.InputStream, byte[]java.sql.Clob java.io.Reader, Stringjava.math.BigInteger ==> Long, Integer, Decimal, Float, Short, java.math.BigDecimaljava.math.BigDecimal ==> Long, Integer, Decimal, Float, Short, java.math.BigInteger== Parameters
Parameters are passed to individual queries but can also be used as a streaming source to prompt the query to be run many times.
Parameters can be named or anonymous. Named parameters are not supported natively by the JDBC specification but rxjava2-jdbc does support them.
This is sql with a named parameter:
select name from person where name=:nameThis is sql with an anonymous parameter:
select name from person where name=?=== Explicit anonymous parameters
In the example below the query is first run with name='FRED' and then name=JOSEPH. Each query returns one result which is printed to the console.
Database.test()
.select("select score from person where name=?")
.parameters("FRED", "JOSEPH")
.getAs(Integer.class)
.blockingForEach(System.out::println);Output is:
21
34=== Flowable anonymous parameters
You can specify a stream as the source of parameters:
Database.test()
.select("select score from person where name=?")
.parameterStream(Flowable.just("FRED","JOSEPH").repeat())
.getAs(Integer.class)
.take(3)
.blockingForEach(System.out::println);Output is:
21
34
21=== Mixing explicit and Flowable parameters
Database.test()
.select("selec暂无开放 Issues,或尚未同步最近议题。