Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: Extend entities definition docs and reference code from snippets #2264

Merged
merged 10 commits into from
Oct 10, 2024
39 changes: 39 additions & 0 deletions documentation-website/Writerside/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Exposed Docs code examples

The `snippets` folder contains a Gradle project with runnable code examples that show how to work with the Exposed library.
Code from these examples is referenced in corresponding documentation sections.

## Run samples

Each example has its own `README` file with instructions on how to run it.
To run an example, you can use a **run** Gradle task that depends on an example location.
For example, to run the `exposed-dao` example, open a new terminal window from the `snippets` folder and execute the following command:

```bash
./gradlew :exposed-dao:run
```

Wait until IntelliJ IDEA builds and runs an example.

## Reference code snippets

To display a specific source file in a topic, use the `code-block` element with the `src` attribute as follows:

### XML

````xml
<code-block lang="kotlin" src="exposed-dao/src/main/kotlin/org/example/StarWarsFilms.kt" />
````

### Markdown

````
```kotlin
```
{src="exposed-dao/src/main/kotlin/org/example/StarWarsFilms.kt"}
````

Use the following additional attributes:
- Use the `include-symbol` attribute to display only a specific function from the source file.
- Use the `include-lines` attribute to display specific lines from the source file.

11 changes: 11 additions & 0 deletions documentation-website/Writerside/snippets/exposed-dao/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Exposed DAO API examples

A Gradle application that shows how to work with Exposed DAO API.

## Run

To run the application, in a terminal window navigate to the `snippets` folder and run the following command:

```shell
./gradlew :exposed-dao:run
```
Original file line number Diff line number Diff line change
@@ -1,13 +1,138 @@
package org.example

import org.example.entities.*
import org.example.tables.*
import org.jetbrains.exposed.dao.id.CompositeID
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.*

fun main() {
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")

transaction {
addLogger(StdOutSqlLogger)
SchemaUtils.create(StarWarsFilms)
createFilms()
createDirectors()
createUsersAndRatings()
}
}

fun createFilms() {
vnikolova marked this conversation as resolved.
Show resolved Hide resolved
SchemaUtils.create(StarWarsFilmsTable)

// Create a new record
val movie = StarWarsFilmEntity.new {
name = "The Last Jedi"
sequelId = 8
director = "Rian Johnson"
}

// Create a new record with id
StarWarsFilmEntity.new(id = 2) {
name = "The Rise of Skywalker"
sequelId = 9
director = "J.J. Abrams"
}

// Read a property value
val movieName = movie.name
println("Created a new film named $movieName")

// Read the id value
val movieId: Int = movie.id.value
println("The id of the new movie is $movieId")

// Read all movies
val allMovies = StarWarsFilmEntity.all()
allMovies.forEach({ println(it.name) })

// Sort results in ascending order
val moviesByAscOrder = StarWarsFilmEntity.all().sortedBy { it.sequelId }
moviesByAscOrder.map { println(it.sequelId) }

// Sort results in descending order
val moviesByDescOrder = StarWarsFilmEntity.all().sortedByDescending { it.sequelId }
moviesByDescOrder.map { println(it.sequelId) }

// Read all with a condition
val specificMovie = StarWarsFilmEntity.find { StarWarsFilmsTable.sequelId eq 8 }
specificMovie.forEach({ println("Found a movie with sequelId 8 and name " + it.name) })

// Get an entity by its id value
val fifthMovie = StarWarsFilmEntity.findById(5)
println(fifthMovie?.name)

// Update an entity value
movie.name = "Episode VIII – The Last Jedi"

// Find by id and update
val updatedMovie = StarWarsFilmEntity.findByIdAndUpdate(5) {
it.name = "Episode VIII – The Last Jedi"
}
println(updatedMovie?.name)

// Find a single record by a condition and update
val updatedMovie2 = StarWarsFilmEntity.findSingleByAndUpdate(StarWarsFilmsTable.name eq "The Last Jedi") {
it.name = "Episode VIII – The Last Jedi"
}
println(updatedMovie2?.name)

// Delete a record
movie.delete()
}

fun createDirectors() {
SchemaUtils.create(DirectorsTable)

val directorId = CompositeID {
it[DirectorsTable.name] = "J.J. Abrams"
it[DirectorsTable.guildId] = UUID.randomUUID()
}

DirectorEntity.new(directorId) {
genre = Genre.SCI_FI
}

// Find records by composite id
/*
SELECT DIRECTORS."name", DIRECTORS.GUILD_ID, DIRECTORS.GENRE
FROM DIRECTORS
WHERE (DIRECTORS."name" = 'J.J. Abrams')
AND (DIRECTORS.GUILD_ID = '2cc64f4f-1a2c-41ce-bda1-ee492f787f4b')
*/
val directors = DirectorEntity.find { DirectorsTable.id eq directorId }
directors.forEach({ println(it.genre) })
}

fun createUsersAndRatings() {
SchemaUtils.create(UsersTable)
SchemaUtils.create(UserRatingsTable)
SchemaUtils.create(CitiesTable)

// Read an entity with a join to another table
val query = UsersTable.innerJoin(UserRatingsTable).innerJoin(StarWarsFilmsTable)
.select(UsersTable.columns)
.where {
StarWarsFilmsTable.sequelId eq 2 and (UserRatingsTable.value greater 5)
}.withDistinct()

val users = UserEntity.wrapRows(query).toList()
users.map { println(it.name) }

CitiesTable.insert {
it[name] = "Amsterdam"
}

// Use a query as an expression to sort cities by the number of users in each city
val expression = wrapAsExpression<Int>(
UsersTable.select(UsersTable.id.count())
.where { CitiesTable.id eq UsersTable.cityId }
)
val cities = CitiesTable.selectAll()
.orderBy(expression, SortOrder.DESC)
.toList()

cities.map { println(it[CitiesTable.name]) }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.example.entities

import org.example.tables.DirectorsTable
import org.jetbrains.exposed.dao.CompositeEntity
import org.jetbrains.exposed.dao.CompositeEntityClass
import org.jetbrains.exposed.dao.id.CompositeID
import org.jetbrains.exposed.dao.id.EntityID

class DirectorEntity(id: EntityID<CompositeID>) : CompositeEntity(id) {
companion object : CompositeEntityClass<DirectorEntity>(DirectorsTable)

var genre by DirectorsTable.genre
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.example.entities

import org.example.tables.StarWarsFilmsTable
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID

class StarWarsFilmEntity(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<StarWarsFilmEntity>(StarWarsFilmsTable)

var sequelId by StarWarsFilmsTable.sequelId
var name by StarWarsFilmsTable.name
var director by StarWarsFilmsTable.director
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.example.entities

import org.example.tables.UsersTable
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID

class UserEntity(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<UserEntity>(UsersTable)

var name by UsersTable.name
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.example.entities

import org.example.tables.UserRatingsTable
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID

class UserRatingEntity(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<UserRatingEntity>(UserRatingsTable)

var value by UserRatingsTable.value
var film by StarWarsFilmEntity referencedOn UserRatingsTable.film // use referencedOn for normal references
var user by UserEntity referencedOn UserRatingsTable.user
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.example.tables

import org.jetbrains.exposed.dao.id.IntIdTable

object CitiesTable : IntIdTable() {
val name = varchar("name", 50)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.example.tables

import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.sql.Column

object DirectorsCustomTable : IdTable<String>("directors") {
vnikolova marked this conversation as resolved.
Show resolved Hide resolved
override val id: Column<EntityID<String>> = varchar("id", 32).entityId()
val name = varchar("name", 50)

override val primaryKey = PrimaryKey(id)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.example.tables

import org.jetbrains.exposed.dao.id.CompositeIdTable

enum class Genre { HORROR, DRAMA, THRILLER, SCI_FI }

object DirectorsTable : CompositeIdTable("directors") {
val name = varchar("name", 50).entityId()
val guildId = uuid("guild_id").autoGenerate().entityId()
val genre = enumeration<Genre>("genre")

override val primaryKey = PrimaryKey(name, guildId)
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example
package org.example.tables

import org.jetbrains.exposed.dao.id.IntIdTable

Expand All @@ -11,7 +11,7 @@ SEQUEL_ID INT NOT NULL,
"name" VARCHAR(50) NOT NULL,
DIRECTOR VARCHAR(50) NOT NULL);
*/
object StarWarsFilms : IntIdTable() {
object StarWarsFilmsTable : IntIdTable() {
val sequelId = integer("sequel_id").uniqueIndex()
val name = varchar("name", MAX_VARCHAR_LENGTH)
val director = varchar("director", MAX_VARCHAR_LENGTH)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.example.tables

import org.jetbrains.exposed.dao.id.IntIdTable

object UserRatingsTable : IntIdTable() {
val value = long("value")
val film = reference("film", StarWarsFilmsTable)
val user = reference("user", UsersTable)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.example.tables

import org.jetbrains.exposed.dao.id.IntIdTable

object UsersTable : IntIdTable() {
val name = varchar("name", 50)
val cityId = reference("cityId", CitiesTable.id)
}
Loading
Loading