百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rxjava2-jdbc

> 前端框架
开源

RxJava2 与 JDBC 的集成,包括非阻塞连接池

395 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

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:

bash
mvn clean install

The project builds fine on Java 8 to 17.

== Getting started Use this maven dependency:

xml

  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):

xml

  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:

java
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:

java
Database db = Database.test(maxPoolSize);

To use the built-in test database you will need the Apache Derby dependency:

xml

  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:

image::https://raw.githubusercontent.com/davidmoten/rxjava2-jdbc/master/rxjava2-jdbc/src/docs/tables.png?raw=true[schema]

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:

java
Database db = Database.test();
db.select("select name from person")
  .getAs(String.class)
  .blockingForEach(System.out::println);

Output is

FRED
JOSEPH
MARMADUKE

Note 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:

java
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:

java
Database.test() 
  .select("select date_of_birth from person where name='FRED'")
  .getAsOptional(Instant.class)
  .blockingForEach(System.out::println);

Output:

Optional.empty

Nulls 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:

java
Database.test()
  .update("update person set date_of_birth = ?") 
  .parameter(null)
  .counts()
  .blockingForEach(System.out::println);

or using named parameters:

java
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):\

java
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:

java
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:

java
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:

java
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:

java
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:

java
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:

java
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:

  • AnnotationsNotFoundException
  • ColumnIndexOutOfRangeException
  • ColumnNotFoundException
  • ClassCastException
  • AutomappedInterfaceInaccessibleException

=== 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

  • Java 8 - Calling a default method on an automapped interface is supported provided the interface is public and you use the default SecurityManager.
  • Java 9 - not supported yet (TODO)

=== Automap with annotated query

The automapped interface can be annotated with the select query:

java
@Query("select name, score from person order by name")
interface Person {
   @Column
   String name();

   @Column
   int score();
}

To use the annotated interface:

java
Database
  .test()
  .select(Person.class)
  .get()
  .map(Person::name)
  .blockingForEach(System.out::println);

Output:

FRED
JOSEPH
MARMADUKE

In fact the .map is not required if you use a different overload of get:

java
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:

kotlin
@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.Date
  • java.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.lang.Long
  • java.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.time.Instant
  • java.sql.Date,java.sql.Time,java.sql.Timestamp ==> java.time.ZonedDateTime
  • java.sql.Blob java.io.InputStream, byte[]
  • java.sql.Clob java.io.Reader, String
  • java.math.BigInteger ==> Long, Integer, Decimal, Float, Short, java.math.BigDecimal
  • java.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:

sql
select name from person where name=:name

This is sql with an anonymous parameter:

sql
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.

java
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:

java
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

java
Database.test()
  .select("selec

Issues· 33 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Javaconcurrencydatabasejavajdbc

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架