An open API service indexing awesome lists of open source software.

https://github.com/itzg/try-postgres-arrays


https://github.com/itzg/try-postgres-arrays

Last synced: 3 months ago
JSON representation

Awesome Lists containing this project

README

          

Tries out:
- [Postgres array types](https://www.postgresql.org/docs/current/arrays.html)
- [Spring Data JDBC](https://docs.spring.io/spring-data/relational/reference/jdbc.html)
- [Liquibase](https://docs.liquibase.com/start/home.html)

## Info

Entity class is declared with a [list field](https://docs.spring.io/spring-data/relational/reference/jdbc/mapping.html#jdbc.entity-persistence.types), `tags`:

```java
@Table("tasks")
public record Task(
@Id
Long id,
String name,
List tags
) {
}
```

In the Liquibase changeset's [createTable](https://docs.liquibase.com/change-types/create-table.html) [columns](https://docs.liquibase.com/change-types/nested-tags/column.html), the type accepts array syntax:

```yaml
- column:
name: tags
type: text[]
```

A [custom query method in the repository interface](https://docs.spring.io/spring-data/relational/reference/jdbc/query-methods.html#jdbc.query-methods.at-query) can be created to retrieve all the tags:

```java
public interface TaskRepository extends CrudRepository {
@Query("SELECT DISTINCT unnest(tags) AS tag FROM tasks ORDER BY tag")
List findAllTags();
}
```

## Usage

Start the Spring Boot app, which starts Postgres via [Compose support](https://docs.spring.io/spring-boot/reference/features/dev-services.html#features.dev-services.docker-compose).

Create a task with tags

```http request
POST http://localhost:8080/tasks
Content-Type: application/json

{
"name": "test3",
"tags": ["blue", "green"]
}
```

Retrieve tasks

```http request
GET http://localhost:8080/tasks
```

Retrieve all task tags

```http request
GET http://localhost:8080/task-tags
```