-
Notifications
You must be signed in to change notification settings - Fork 11
User Defined Objects as Columns
SqliteMagic supports user defined objects as columns (or "complex columns") without any hustle, complications or special configuration. Just define a complex column as a normal column and that's it.
Prerequisite for defining complex columns is that the parent and child objects are both included in the database schema with both having @Table
annotations.
Example:
POJO | Result in SQL |
---|---|
@Table(persistAll = true)
public class Author {
String firstName;
String lastName;
...
}
@Table(persistAll = true)
public class Book {
String title;
Author author;
...
} |
CREATE TABLE IF NOT EXISTS author (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name TEXT,
last_name TEXT
);
CREATE TABLE IF NOT EXISTS book (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author INTEGER
);
|
Internally, the referenced table id is saved in a parent table (as seen in example: author INTEGER
). Note that there is no foreign key constraint - there is no real need for it and in that way, we can keep things simple (e.g. in migrations).
By default, when a parent object is persisted (in the example above it's the Book object), its complex columns are also persisted. In that case, the whole operation is internally wrapped inside a transaction (source code can be viewed in the generated code).
Java | Result in Database | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Author author = new Author("Foo", "Bar");
Book book = new Book("The Bar Life", author);
long id = book
.persist()
.execute();
|
Author:
Book:
|
If the functionality mentioned above is not needed, annotate column with @Column(handleRecursively = false)
. In that case, only the referenced table id is persisted.
@Table(persistAll = true)
public class Book {
String title;
@Column(handleRecursively = false)
Author author;
...
}
Author author = new Author("Foo", "Bar");
Book book = new Book("The Bar Life", author);
// no changes to Author table here
long id = book
.persist()
.execute();
If the ON DELETE CASCADE
constraint is needed, annotate complex column with @Column(onDeleteCascade = true)
.
The default value is false.
POJO | Result in SQL |
---|---|
@Table(persistAll = true)
public class Book {
String title;
@Column(onDeleteCascade = true)
Author author;
...
} |
CREATE TABLE IF NOT EXISTS book (
_id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
author INTEGER REFERENCES author(_id) ON DELETE CASCADE
);
|