- Install Java connector
- Run Tarantool
- Update deps in pom.xml
- Package and run Hello world app
- Build classpath to use it in Jshell
- Run Jshell with classpath
- Import needed classes
- Run get version
- Create space
- Insert List into Tarantool and select it
- Insert Map into Tarantool and select it
- Insert POJO into Tarantool and select it
Установить коннектор по инструкции.
docker run -p 3301:3301 -it tarantool/tarantoolmvn archetype:generate -DgroupId=com.example -DartifactId=my-tarantool-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=falsecd my-tarantool-app
cat > pom.xml <<EOL
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-tarantool-app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.tarantool</groupId>
<artifactId>tarantool-client</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
EOLmvn package && mvn exec:java -Dexec.mainClass="com.example.App"mvn dependency:build-classpath -Dmdep.outputFile=classpath.txtjshell --class-path $(cat classpath.txt):target/classesimport java.util.*;
import java.time.*;
import io.tarantool.core.*;
import io.tarantool.balancer.*;
import io.tarantool.mapping.*;
import io.tarantool.pool.*;
import io.tarantool.schema.*;
import io.tarantool.client.*;
import io.tarantool.client.factory.*;
import io.tarantool.client.crud.*;
import io.tarantool.mapping.crud.*;
import io.tarantool.mapping.*;
import io.tarantool.client.crud.options.*;
import static io.tarantool.mapping.BaseTarantoolJacksonMapping.objectMapper;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.type.*;var client = TarantoolFactory.box().build();
var f = client.eval("return _TARANTOOL");
f.join();Т.к. в обычном тарантуле нет миграций, то мы создадим спейс(так называется таблица в тарантуле) напрямую.
client.eval("return box.schema.create_space('person'):create_index('pk')").join();client.space("person").insert(Arrays.asList(1, "hello world", Instant.now())).join();
var space = client.space("person");
space.select(1).join();Зафиксируем формат.
client.eval("""
box.space.person:format({
{'id', 'integer'},
{'name', 'string'},
{'createdAt', 'datetime'},
{'metadata', 'map', is_nullable = true}
})
""").join();Получим ошибку, т.к. мы зафиксировали формат.
space.insert(Arrays.asList(2, 3)).join();Вставим корректную формату запись, чтобы убедится, что после создания формата вставка все еще работает.
space.insert(Arrays.asList(2, "ivan", Instant.now())).join();Тарантул как синглинстанс оперирует только flatten вида объектами, т.е. ему можно прописать
формат, но все так же принимать он будет сжатые таплы в виде массива.
Поэтому мапку можно сохранять в поле, которое мы назвали map.
client.space("person").insert(Arrays.asList(3, "hello world", Instant.now(), Map.of("data_uuid", UUID.randomUUID(), "data", "secret_data"))).join();Но можно ли сохранять Map в базовом виде?
На самом деле можно сохранять Map, но в рамках OpenSource single instance версии
нужно будет написать какой-то код, который будет работать с ключами.
Или все время переводить Map в список, сохраняя правильный порядок полей.
Например вот таким способ можно использовать POJO:
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonIgnoreProperties(ignoreUnknown = true) // for example bucket_id
public class Person {
public Integer id;
public String name;
public Instant createdAt;
public Map metadata;
public Person() {
}
public Person(Integer id, String name, Instant createdAt, Map metadata) {
this.id = id;
this.name = name;
this.createdAt = createdAt;
this.metadata = metadata;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", createdAt=" + createdAt +
", metadata=" + metadata +
'}';
}
}space.insert(new Person(4, "hello world", Instant.now(), Map.of("data_uuid", UUID.randomUUID(), "data", "secret_data"))).join();space.select(4).join();
space.select(Arrays.asList(4), Person.class).join();Это все магия
@JsonFormat(shape = JsonFormat.Shape.ARRAY)Можно записывать и без этой аннотации и мапки напрямую, но это уже выходить за рамки данной практики. Подробнее можно почитать здесь https://tarantool.github.io/tarantool-java-ee/markdown/tuple_pojo_mapping.html