-
Notifications
You must be signed in to change notification settings - Fork 0
Home
- 09/12 - atividade avaliada
- https://cheatsheets.zip/postgres
- https://cheatsheets.zip/redis
- https://cheatsheets.zip/mongodb
- https://cheatsheets.zip/neo4j
-
Dependendo da versão da JDK instalada, pode ser necessário trocar no pom.xml:
-
Isto:
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
- Por:
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
ou 20, ou 22
- Banco de Dados - DesCOMPlica, Oliba!
- Curso Básico de PostgreSQL
- DesCOMPlica, oliba! - Como Programar PostgreSQL
- Como instalei o PostgreSQL na minha máquina?
- JPA
- @OneToOne
- @OneToMany
- JPA: Herança
- JPA: @ManyToMany
- JPA: JPQL
- JPA: NameQuery
- JPA: NativeQuery
- JPA: Engenharia Reversa
- Quando NÃO usar SQL?
- Jedis
Links Complementares:
-
https://neo4j.com/docs/cypher-manual/current/clauses/load-csv/#query-load-csv-introduction
-
https://github.com/santanche/lab2learn/blob/master/network/cypher/s01exercises/s01b-cypher-basics.md
-
https://github.com/santanche/lab2learn/blob/master/network/cypher/s01exercises/s02b-cypher-faers.md
-
https://neo4j.com/docs/cypher-manual/current/clauses/create/
CSV - Disciplinas e Pré-requisitos:
CSV - Amigos e Amizades:
-
- obs: usando o MERGE
-
Instalação
-- 1ª vez
sudo docker run \
--publish=7474:7474 --publish=7687:7687 \
--volume=$HOME/neo4j/data:/data \
--env=NEO4J_AUTH=neo4j/password \
--name neo4j neo4j
-- demais vezes
sudo docker start neo4j
sudo docker exec -it neo4j bash
Obs: Acessar por http://localhost:7474/
login: neo4j e senha: password
-- criar um nó
CREATE(p:Pessoa{cpf: "111.111.111-11", nome: "joao", idade:20})
return p
-- retornar todas pessoas
MATCH(p:Pessoa) RETURN p
-- select
match(p:Pessoa) where p.cpf = "111.111.111-11"
return p
match(p:Pessoa) where p.cpf = "111.111.111-11" or ....
return p
match(p:Pessoa) where p.cpf = "111.111.111-11" and ....
return p
-- amigos dos meus amigos (eu sendo "Pedro"). Retorno: "João"
MATCH (:Pessoa{nome: "Pedro"})<-[:AMIGO]-()<-[:AMIGO]-(p) return p
-- criar uma aresta entre nodos
-- exemplo 1
MATCH (p1:Pessoa), (p2:Pessoa)
where p1.nome = "João" and p2.nome = "Maria"
CREATE (p1)-[:AMIGO]->(p2)
-- exemplo 2
MATCH (p1:Pessoa), (p2:Pessoa)
where ID(p1) = 10 and ID(p2) = 11
CREATE (p1)-[:AMIGO]->(p2)
-- exemplo3 (criando os nodos e a aresta ao mesmo tempo)
CREATE (a:a {a: 'a'})-[r:a]->(b:a {a: 'a'})
-- aresta com atributo
MATCH (p1:Pessoa), (p2:Pessoa)
WHERE p1.nome = "João" AND p2.nome = "Maria"
CREATE (p1)-[:AMIGO1{desde:"19/11/2020"}]->(p2)
-- update
MATCH (p:Pessoa) where p.nome = "Pedro"
set p.nome = "Pedro silva"
-- delete o nodo
MATCH (p:Pessoa) where p.nome = "Pedro silva"
Delete p
-- deletar relacionamentos AMIGO de joão
MATCH (:Pessoa{nome: 'joao'})-[a:AMIGO]-()
DELETE a
-- delete o nodo e seus relacionamentos
MATCH (p:Pessoa) where p.nome = "Pedro silva"
detach Delete p
-- delete tudo
MATCH (n)
DETACH DELETE n
Driver JAVA-NEO4J:
<dependencies>
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>4.4.0</version>
</dependency>
</dependencies>
package view;
import model.Pessoa;
import org.neo4j.driver.*;
import java.time.LocalDate;
import java.util.stream.Collectors;
import static org.neo4j.driver.Values.parameters;
public class App {
public static void main(String[] args) {
Driver driver = GraphDatabase.driver("bolt://localhost:7687",
AuthTokens.basic("neo4j", "neo4j*"));
Pessoa pessoa = new Pessoa("222.222.222-02", "Maria",
LocalDate.of(1993,10,25));
try(Session session = driver.session()){
// Adicionando uma pessoa
Result result = session.run("CREATE (p:Pessoa{cpf:$cpf, nome:$nome, nascimento:$nascimento})",
parameters("cpf", pessoa.getCpf(), "nome", pessoa.getNome(),
"nascimento", pessoa.getNascimento()));
System.out.println(result.consume().counters().nodesCreated());
// Criar um relacionamento
Result result = session.run("MATCH (p1:Pessoa{cpf:$cpf}),(p2:Pessoa{cpf:$cpf2})" +
"CREATE (p1)-[:AMIGO]->(p2)",
parameters("cpf", "111.111.111-01", "cpf2", "222.222.222-02"));
System.out.println(result.consume().counters().relationshipsCreated());
// Recuperando todas as pessoas
Result result = session.run("MATCH (p:Pessoa) RETURN p.cpf, p.nome, p.nascimento");
System.out.println(result.stream().map(record ->
new Pessoa(record.get(0).asString(),
record.get(1).asString(),
record.get(2).asLocalDate()))
.collect(Collectors.toList()));
// Buscando os CPFs de todos os amigos de uma pessoa
Result result = session.run("MATCH (p:Pessoa{cpf:$cpf})-[:AMIGO]->(p2) RETURN p2",
parameters("cpf", "111.111.111-01"));
result.list().forEach(r -> System.out.println(r.get(0).asNode().values()));
} finally {
driver.close();
}
}
}
Links Complementares:
- https://neo4j.com/docs/cypher-manual/current/introduction/
- https://neo4j.com/docs/cypher-manual/current/clauses/create/
- https://github.com/santanche/lab2learn/blob/master/network/cypher/s01exercises/s01b-cypher-basics.md
- https://neo4j.com/developer/java/
- https://neo4j.com/docs/java-manual/current/get-started/
Vídeos:
Material Complementar:
-
https://www.mongodb.com/docs/manual/reference/operator/query/
-
https://www.mongodb.com/docs/manual/reference/operator/query-comparison/
-
❗ https://www.mongodb.com/docs/manual/core/aggregation-pipeline/
-
Mongo Java Driver com Pojo:
Outros:
- https://www.mongodb.com/docs/manual/tutorial/insert-documents/
- https://www.mongodb.com/docs/manual/tutorial/query-documents/
- https://www.mongodb.com/docs/manual/tutorial/query-arrays/
- https://www.mongodb.com/docs/manual/reference/operator/query/#std-label-query-selectors
- https://www.mongodb.com/docs/manual/core/aggregation-pipeline/#std-label-aggregation-pipeline-examples
- https://studio3t.com/knowledge-base/articles/mongodb-aggregation-framework/
- https://www.mongodb.com/docs/manual/applications/data-models/
- Principais Comandos
-- Criando/Selecionar um BD
use minhaBase
-- retornar collection users
1) db.users
2) db.getCollection("users")
-- inserir
db.users.insert({"name": "codigo"}) -- legacy
db.users.insertOne({"name": "codigo"}) -- current
-- listar todos
db.users.find()
-- Update
db.users.update({"name": "Igor"},{"name": "novo"}) -- legacy
db.users.updateOne({"name": "Igor"},{$set:{"name":"Igor Pereira"}}) -- current
-- Delete
db.users.remove({"name": "codigo"}) -- legacy
db.users.deleteOne({"name": "codigo"}) -- current
Links:
- https://www.mongodb.com/docs/manual/crud/
- https://www.mongodb.com/docs/manual/tutorial/insert-documents/
- https://www.mongodb.com/docs/manual/tutorial/query-documents/#query-documents
-
MongoDB Java Driver - Quick Start
-
Connect to MongoDB: https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/connection/connect/#std-label-connect-to-mongodb
-
URI de Conexão
-
String uri = "mongodb://localhost:27017";
-
MongoDB Java Driver - Examples
- Instalação via Maven
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
References:
- insertOne: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/insertOne/
- updateOne: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/updateOne/
- deleteOne: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/deleteOne/
- findOne: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/findOne/
- findMany: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/find/
- count: https://www.mongodb.com/docs/drivers/java/sync/current/usage-examples/count/
- ❗ https://mongodb.github.io/mongo-java-driver/3.7/driver/getting-started/quick-start-pojo/
- ❗ java-mapping-pojos: https://www.mongodb.com/developer/languages/java/java-mapping-pojos/
Extras:
- Tutorial
- https://www.mongodb.com/docs/guides/crud/read_queries/
- ❗ https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/crud/read-operations/
- ❗ https://www.mongodb.com/docs/manual/reference/operator/
- ❗ https://www.mongodb.com/docs/manual/reference/sql-comparison/
- robo 3t
-- updateOne
try {
db.users.updateOne(
{ "nome" : "max" },
{ $set: { "nome" : "maximiliano" } }
);
} catch (e) {
print(e);
}
-- removeOne
try {
db.users.deleteOne( { "_id" : ObjectId("634dea8922941a787369e69a")} );
} catch (e) {
print(e);
}
-- find
db.users.find({"nome": "igor"})
db.users.find({nome:{$in:["igor", "erick"]}})
Instalação Ubuntu/Debian/Linux Mint
sudo apt-get update
sudo apt-get install redis-server
Instalação Docker
-- 1ª vez
docker run --name redis -p 6379:6379 -d redis:latest
docker exec -it redis redis-cli
-- demais vezes
sudo docker start redis
sudo docker exec -it redis redis-cli
Client
redis-cli
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.0</version>
</dependency>
-- 1)
JedisPool pool = new JedisPool("localhost", 6379);
try (Jedis jedis = pool.getResource()) {
jedis.set("clientName", "Jedis");
}
-- 2)
JedisPooled jedis = new JedisPooled("localhost", 6379);
Links:
GSON:
Gson
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Se usar datas (LocalDate ou LocalDateTime) será preciso serializar e deserializar:
- Criar um objeto Gson com GsonBuilder:
-- se for LocalDate
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
.create();
-- se for LocalDateTime
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeTypeAdapter())
.create();
- Construir uma classe concreta que implemente JsonSerializer e JsonDeserializer
- No caso de ser LocalDate:
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import com.google.gson.*;
public class LocalDateTypeAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
@Override
public JsonElement serialize(final LocalDate date, final Type typeOfSrc,
final JsonSerializationContext context) {
return new JsonPrimitive(date.format(formatter));
}
@Override
public LocalDate deserialize(final JsonElement json, final Type typeOfT,
final JsonDeserializationContext context) throws JsonParseException {
return LocalDate.parse(json.getAsString(), formatter);
}
}
- No caso de ser LocalDateTime:
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.google.gson.*;
public class LocalDateTimeTypeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss");
@Override
public JsonElement serialize(LocalDateTime localDateTime, Type srcType,
JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDateTime));
}
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return LocalDateTime.parse(json.getAsString(), formatter);
}
}
Type listType = new TypeToken<ArrayList<ArrayItem>>(){}.getType();
ArrayList<ArrayItem> list = gson.fromJson(jsonSource, listType);
Vídeo Complementar:
Alternativas open-source:
obs: o código já tem um exemplo de JEDIS (driver jdbc para JAVA e Redis)
JPA - @ManyToMany