Einführung in Lightsleep, eine O / R-Zuordnungsbibliothek, die nur mit Java Runtime- und JDBC-Treibern funktioniert

Lightsleep ist eine kompakte O / R-Zuordnungsbibliothek (Object-Relational), die in Java 8 und höher verfügbar ist.

Änderungsprotokoll

--2017-01-14 --3-1-15. Beispiel für SELECT COUNT (*) und SQL-Beispiel (PostgrSQL, Oracle, SQL Server) hinzugefügt --2017-01-29- * Version 1.7.0 * kompatibel (SQLite-kompatibel) --2017-02-11- * Version 1.8.0 * unterstützt (@ColumnType, @ColumnTypeProperty hinzugefügt) --2017-02-18 - Die Beschreibung des JDBC-Treibers für SQL Server im Beispiel build.gradle wurde korrigiert. --2017-02-26- * Version 1.8.2 * kompatibel --2017-04-16 - Download zum Link ändern --2017-06-05- * Version 1.9.0 * kompatibel (DB2 kompatibel) --2017-09-09- * Version 2.0.0 * kompatibel, Beschreibungsbeispiel in Groovy hinzugefügt --2017-11-14- * Version 2.1.0 * unterstützt (mehrere JDBC-URLs unterstützt) --2017-12-06 - Es wurde ein Beschreibungsbeispiel für lightleep.properties hinzugefügt, das mehrere Datenquellen mit Jndi angibt. --2018-10-07- * Version 3.0.0 * unterstützt (DateTime-API-Typ unterstützt) --2019-07-17- * Version 3.1.0 * unterstützt (FROM-Klausel-Unterabfrage, UNION SQL-Erstellung unterstützt) --2019-09-25- * Version 3.2.0 * kompatibel (MariaDB kompatibel)

Charakteristisch

--API mit in Java 8 hinzugefügten Funktionen (Funktionsschnittstelle, optionale Klasse).

Verknüpfung

build.gradle

Beschreibungsbeispiel:

build.gradle


apply plugin: 'java-library'

repositories {
    jcenter()
}

dependencies {
    compile 'org.lightsleep:lightsleep:3.2.0'
}

Beschreibungsbeispiel, wenn die Protokollierungsbibliothek, der JDBC-Treiber und die Verbindungspoolbibliothek hinzugefügt werden:

build.gradle


apply plugin: 'java-library'

repositories {
    jcenter()
}

dependencies {
    compile 'org.lightsleep:lightsleep:3.2.0'

    //Bei Verwendung einer Protokollierungsbibliothek
    runtimeOnly 'log4j:log4j:1.2.17'                            // Log4j
    runtimeOnly 'org.apache.logging.log4j:log4j-core:2.12.1'    // Log4j2
    runtimeOnly 'ch.qos.logback:logback-classic:1.2.3'          // LogBack

    //Einer der folgenden oder andere JDBC-Treiber
    runtimeOnly 'com.ibm.db2.jcc:db2jcc4:db2jcc4'               // DB2
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client:2.4.4'    // MariaDB
    runtimeOnly 'mysql:mysql-connector-java:8.0.17'             // MySQL
    runtimeOnly 'com.oracle.ojdbc:ojdbc8:19.3.0.0'              // Oracle
    runtimeOnly 'org.postgresql:postgresql:42.2.8'              // PostgreSQL
    runtimeOnly 'org.xerial:sqlite-jdbc:3.28.0'                 // SQLite
    runtimeOnly 'com.microsoft.sqlserver:mssql-jdbc:7.4.1.jre8' // SQLServer

    //Bei Verwendung der Verbindungspoolbibliothek
    runtimeOnly 'com.mchange:c3p0:0.9.5.4'                      // C3p0
    runtimeOnly 'org.apache.commons:commons-dbcp2:2.7.0'        // Dbcp
    runtimeOnly 'com.zaxxer:HikariCP:3.4.1'                     // HikariCP
    runtimeOnly 'org.apache.tomcat:tomcat-jdbc:9.0.26'          // TomcatCP
}

wie benutzt man

1. Erstellen einer Entitätsklasse

Definieren Sie für jede Tabelle in der Datenbank eine Entitätsklasse (einen Container für Daten).

Definitionsbeispiel:

Contact.java


package org.lightsleep.example.entity;

import java.sql.Date;
import org.lightsleep.entity.*;

public class Contact {
    @Key
    public int       id;
    public String    firstName;
    public String    lastName;
    public LocalDate birthday;
}

Phone.java


package org.lightsleep.example.entity;

import org.lightsleep.entity.*;

public class Phone {
    @Key
    public int    contactId;
    public short  childIndex;
    public String label;
    public String content;
}

Contact.groovy


package org.lightsleep.example.entity

import java.sql.Date
import org.lightsleep.entity.*

class Contact {
    @Key
    int       id
    String    firstName
    String    lastName
    LocalDate birthday
}

Phone.groovy


package org.lightsleep.example.entity

import org.lightsleep.entity.*

class Phone {
    @Key
    int    contactId
    short  childIndex
    String label
    String content
}

Im obigen Beispiel ist das Feld "public" definiert, es ist jedoch in Ordnung, das Feld "private" und die Methode "public getter / setter" zu kombinieren. Die getter Methode kann mit is oder keinem Präfix zusätzlich zum get Präfix durchgeführt werden. Die setter Methode unterstützt auch mit oder ohne das set Präfix.

Java


private int id;
public int getId() {return id;}
public void setId(int id) {this.id = id;}

Groovy


int id
int getId() {return id}
void setId(int id) {this.id = id}

Wenn der Klassenname und der zugehörige Tabellenname unterschiedlich sind, fügen Sie der Klasse "@ Table" hinzu.

Java


import org.lightsleep.entity.*;

@Table("CONTACTS")
public class Contact {

Groovy


import org.lightsleep.entity.*

@Table('CONTACTS')
public class Contact {

Hängen Sie "@ Key" an das Feld an, das der Spalte der Primärschlüssel entspricht.

Wenn der Spaltenname und der Feldname unterschiedlich sind, fügen Sie dem Feld "@ Column" hinzu.

Java


import org.lightsleep.entity.*;
    ...
    @Column("LAST_NAME")
    public String lastName;

Groovy


import org.lightsleep.entity.*
    ...
    @Column('LAST_NAME')
    String lastName

Wenn der Spaltentyp und der Feldtyp unterschiedlich sind, fügen Sie dem Feld "@ ColumnType" hinzu.

Java


import org.lightsleep.entity.*;
    ...
    @ColumnType(Long.class)
    public LocalDate birthday;

Groovy


import org.lightsleep.entity.*
    ...
    @ColumnType(Long)
    LocalDate birthday

Nicht statische Felder werden automatisch Spalten zugeordnet. Fügen Sie daher "@ NonColumn" zu Feldern hinzu, die sich nicht auf Spalten beziehen.

Java


import java.util.ArrayList;
import java.util.List;
import org.lightsleep.entity.*;
    ...
    @NonColumn
    public List<Phone> phones = new ArrayList<>();

Groovy


import org.lightsleep.entity.*
    ...
    @NonColumn
    List<Phone> phones = []

Wenn SQL anstelle eines Feldwerts einen Ausdruck angeben soll, fügen Sie "@ Select", "@ Insert", "@ Update" hinzu. Wenn Sie angeben möchten, dass es nicht für SQL verwendet wird, fügen Sie "@ NonSelect", "@ NonInsert", "@ NonUpdate" hinzu.

Java


import java.time.LocalDateTime;
import org.lightsleep.entity.*;
    ...
    @Insert("0")
    @Update("{updateCount}+1")
    public int updateCount;

    @Insert("CURRENT_TIMESTAMP")
    @NonUpdate
    public LocalDateTime createdTime;

    @Insert("CURRENT_TIMESTAMP")
    @Update("CURRENT_TIMESTAMP")
    public LocalDateTime updatedTime;

Groovy


import java.time.LocalDateTime
import org.lightsleep.entity.*
    ...
    @Insert('0')
    @Update('{updateCount}+1')
    int updateCount

    @Insert('CURRENT_TIMESTAMP')
    @NonUpdate
    LocalDateTime createdTime

    @Insert('CURRENT_TIMESTAMP')
    @Update('CURRENT_TIMESTAMP')
    LocalDateTime updatedTime

Es hat die folgenden Anmerkungen.

Name der Anmerkung Inhalt angegeben werden Zu spezifizierendes Ziel
@Table Tabellenname Klasse
@Key Unterstützt Primärschlüssel Feld
@Column Spaltenname Feld
@ColumnType Spaltentyp Feld
@NonColumn Nicht in Bezug auf Spalten Feld
@NonSelect Wird nicht für SELECT SQL verwendet Feld
@NonInsert Wird nicht für INSERT SQL verwendet Feld
@NonUpdate Wird nicht für UPDATE SQL verwendet Feld
@Select In SELECT SQL verwendete Ausdrücke Feld
@Insert In INSERT SQL verwendete Ausdrücke Feld
@Update In UPDATE SQL verwendete Ausdrücke Feld
@KeyProperty Unterstützt Primärschlüssel Klasse
@ColumnProperty Spaltenname Klasse
@ColumnTypeProperty Spaltentyp Klasse
@NonColumnProperty Nicht in Bezug auf Spalten Klasse
@NonSelectProperty Wird nicht für SELECT SQL verwendet Klasse
@NonInsertProperty Wird nicht für INSERT SQL verwendet Klasse
@NonUpdateProperty Wird nicht für UPDATE SQL verwendet Klasse
@SelectProperty In SELECT SQL verwendete Ausdrücke Klasse
@InsertProperty In INSERT SQL verwendete Ausdrücke Klasse
@UpdateProperty In UPDATE SQL verwendete Ausdrücke Klasse

@XxxxxProperty wird verwendet, um Felder anzugeben, die in Oberklassen definiert sind. Sie können dieselbe Anmerkung in einer Klasse mehrmals angeben.

2. Definition vonightsleep.properties

Definitionsbeispiel:

lightsleep.properties


Logger      = Log4j2
#Database   =PostgreSQL * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = Dbcp
url         = jdbc:postgresql://postgresqlserver/example
username    = example
password    = _example_
initialSize = 10
maxTotal    = 100

Logger ist eine Spezifikation der Methode zur Ausgabe des Protokolls und wählen Sie eine der folgenden Optionen aus.

Angegebener Inhalt Zu verwendende Protokollierungsbibliothek Protokollstufe Definitionsdatei
Jdk Java Runtime logging.In Eigenschaften definiert
Log4j Log4j 1.x.x log4j.Eigenschaften oder log4j.In XML definiert
Log4j2 Log4j 2.x.x log4j2.In XML definiert
SLF4J SLF4J Hängt von der Implementierung der Zielprotokollierungsbibliothek ab
Std$Out$Trace System.Ausgabe nach außen trace
Std$Out$Debug Das gleiche wie oben debug
Std$Out$Info Das gleiche wie oben info
Std$Out$Warn Das gleiche wie oben warn
Std$Out$Error Das gleiche wie oben error
Std$Out$Fatal Das gleiche wie oben fatal
Std$Err$Trace System.Ausgabe zu err trace
Std$Err$Debug Das gleiche wie oben debug
Std$Err$Info Das gleiche wie oben info
Std$Err$Warn Das gleiche wie oben warn
Std$Err$Error Das gleiche wie oben error
Std$Err$Fatal Das gleiche wie oben fatal

Wenn nicht angegeben, wird "Std $ Out $ Info" ausgewählt.

~~ Datenbank ist die Spezifikation des Ziel-DBMS und wird aus den folgenden ausgewählt. ~~

~~ Wenn Sie ein anderes DBMS als das oben genannte verwenden möchten, geben Sie es nicht an oder geben Sie "Standard" an. ~~

ConnectionSupplier wird aus den folgenden Optionen ausgewählt, indem der zu verwendende Verbindungslieferant (Verbindungspool usw.) angegeben wird.

Angegebener Inhalt Verbindungslieferant
C3p0 c3p0
Dbcp Apache Commons DBCP
HikariCP HikariCP
TomcatCP Tomcat JDBC Connection Pool
Jndi Java Naming and Directory Interface (JNDI) (Für Tomcat)
Jdbc DriverManager#getConnection(String url, Properties info)Methode

Unterhalb des Verbindungslieferanten (url ~ maxTotal) im obigen Definitionsbeispiel fürightsleep.properties befindet sich der Definitionsinhalt, der an jeden Verbindungslieferanten übergeben werden soll.

Definitionsbeispiel (Std $ Out $ Info / DB2 / Jdbc):

lightsleep.properties


Logger    = Std$Out$Info
#Database =DB2 * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = Jdbc
url       = jdbc:db2://db2:50000/example

Definitionsbeispiel (Jdk / MySQL / C3p0):

lightsleep.properties


Logger    = Jdk
#Database =MySQL * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = C3p0
url       = jdbc:mysql://mysql:3306/example
user      = example
password  = _example_

Andere Definitionen als URL, Benutzer und Kennwort werden in c3p0.properties oder c3p0-config.xml beschrieben.

Definitionsbeispiel (Log4j / Oracle / Dbcp):

lightsleep.properties


Logger      = Log4j
#Database   =Oracle * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = Dbcp
url         = jdbc:oracle:thin:@oracle:1521:example
username    = example
password    = _example_
initialSize = 10
maxTotal    = 100
   ...

Definitionsbeispiel (Log4j2 / PostgreSQL / HikariCP):

lightsleep.properties


Logger          = Log4j2
#Database       =PostgreSQL * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = HikariCP
jdbcUrl         = jdbc:postgresql://postgresql:5432/example
username        = example
password        = _example_
minimumIdle     = 10
maximumPoolSize = 100
   ...

Definitionsbeispiel (SLF4J / SQLServer / TomcatCP):

lightsleep.properties


Logger      = SLF4J
#Database   =SQLServer * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = TomcatCP
url         = jdbc:sqlserver://sqlserver:1433;database=example
username    = example
password    = _example_
initialSize = 10
maxActive   = 100
   ...

Definitionsbeispiel (Log4j / MySQL / Jndi):

lightsleep.properties


Logger             = Log4j
#Database           =MySQL * Version 2.1.Bei 0 abgeschafft
ConnectionSupplier = Jndi
dataSource         = jdbc/example

Definitionsbeispiel für mehrere JDBC-URLs 1

** (Version 2.1.0 ~) **

lightsleep.properties


#Bei Angabe mehrerer JDBC-URLs
Logger      = Log4j2
ConnectionSupplier = Dbcp
urls        = jdbc:postgresql://postgresql:5432/example,\
              jdbc:postgresql://postgresql:5433/example
user        = example
password    = _example_
initialSize = 10
maxTotal    = 100

Definitionsbeispiel für mehrere JDBC-URLs 2

** (Version 2.1.0 ~) **

lightsleep.properties


#Bei Verwendung mehrerer DBMS(Geben Sie Benutzer und Passwort in der URL an)
Logger = Log4j2
ConnectionSupplier = Dbcp
urls = \
    jdbc:db2://db2:50000/example:user=example;password=_example_;,\
    jdbc:mariadb://mariadb:3306/example?user=example&password=_example_,\
    jdbc:mysql://mysql:3306/example?user=example&password=_example_,\
    jdbc:oracle:thin:example/_example_@oracle:1521:example,\
    jdbc:postgresql://postgresql:5432/example?user=example&password=_example_,\
    jdbc:sqlite:C:/sqlite/example,\
    jdbc:sqlserver://sqlserver:1433;database=example;user=example;password=_example_,\
      <Leerzeile>
initialSize = 10
maxTotal    = 100

Definitionsbeispiel für mehrere JDBC-URLs 3

** (Version 2.1.0 ~) **

lightsleep.properties


#Bei der Angabe eines Verbindungsanbieters für jede URL
Logger = Log4j2
urls = \
    [  Jdbc  ]jdbc:db2://db2:50000/example:user=example;password=_example_;,\
    [  C3p0  ]jdbc:mariadb://mariadb:3306/example?user=example&password=_example_,\
    [  Dbcp  ]jdbc:mysql://mysql:3306/example?user=example&password=_example_,\
    [HikariCP]jdbc:oracle:thin:example/_example_@oracle:1521:example,\
    [TomcatCP]jdbc:postgresql://postgresql:5432/example?user=example&password=_example_,\
    [  Jdbc  ]jdbc:sqlite:C:/sqlite/example,\
    [  C3p0  ]jdbc:sqlserver://sqlserver:1433;database=example;user=example;password=_example_,\
      <Leerzeile>
# Dbcp, HikariCP, TomcatCP
initialSize = 10

# Dbcp
maxTotal    = 10

# TomcatCP
maxActive   = 10

# HikariCP
minimumIdle     = 10
maximumPoolSize = 10

Definitionsbeispiel für mehrere Datenquellen 4

** (Version 2.1.0 ~) ** ** (2017-12-06 postscript) **

Bei der Definition von * dataSource / dataSources ist im Gegensatz zu url / urls das Schlüsselwort, das den Datenbankhandler identifiziert, (in einigen Fällen) nicht enthalten, sodass die URL aus DatabaseMetaData des zuerst erhaltenen und beurteilten Verbindungsobjekts abgerufen wird. .. * ** (Version 2.1.1 ~) **

lightsleep.properties


#Bei Verwendung von Jndi
Logger = Log4j2
ConnectionSupplier = Jndi
dataSources = \
    jdbc/db2_example,\
    jdbc/mariadb_example,\
    jdbc/mysql_example,\
    jdbc/oracle_example,\
    postgresql_example,\
    sqlite_example,\
    sqlserver_example,\
      <Leerzeile>
#   ↑"jdbc/"Mit oder ohne

3. Datenbankzugriff

Das Ausführen der Methode "Transaction.execute" entspricht dem Ausführen einer Transaktion. Der Inhalt der Transaktion wird durch das Argument "Transaktion" (Lambda-Ausdruck) definiert. Der Lambda-Ausdruck entspricht dem Inhalt der Methode "Transaction.executeBody", und das Argument dieser Methode lautet "Connection".

Java


Contact contact = new Contact(1, "Akane", "Apple");

//Transaktionsbeispiel
Transaction.execute(conn -> {
    //Transaktionsstart
    new Sql<>(Contact.class).connection(conn)
        .insert(contact);
   ...
    //Ende der Transaktion
});

Groovy


def contact = new Contact(1, 'Akane', 'Apple')

//Transaktionsbeispiel
Transaction.execute {
    //Transaktionsstart
    new Sql<>(Contact).connection(it)
        .insert(contact)
    ...
    //Ende der Transaktion
}

Wenn Sie mehrere JDBC-URLs (oder Datenquellen) in "ightsleep.properties "definiert haben, müssen Sie angeben, für welche URL (oder Datenquelle) die Transaktion ausgeführt werden soll. Die Methode "ConnectionSupplier.find" sucht nach einer URL (oder Datenquelle), die das gesamte Zeichenfolgenarray (variable Argumente) ihrer Argumente enthält. Eine Ausnahme wird ausgelöst, wenn mehr als eine gefunden oder nicht gefunden wird. ** (Version 2.1.0 ~) **

lightsleep.properties


urls = jdbc:postgresql://postgresql:5432/example1,\
       jdbc:postgresql://postgresql:5432/example2,\
       jdbc:postgresql://postgresql:5433/example1,\
       jdbc:postgresql://postgresql:5433/example2

Java


public static final ConnectionSupplier supplier1 = ConnectionSupplier.find("5432", "example1");
public static final ConnectionSupplier supplier2 = ConnectionSupplier.find("5432", "example2");
public static final ConnectionSupplier supplier3 = ConnectionSupplier.find("5433", "example1");
public static final ConnectionSupplier supplier4 = ConnectionSupplier.find("5433", "example2");
    ...

Contact contact = new Contact(1, "Akane", "Apple");

//Transaktionsbeispiel
Transaction.execute(supplier1, conn -> {
    //Transaktionsstart
    new Sql<>(Contact.class).connection(conn)
        .insert(contact);
   ...
    //Ende der Transaktion
});

Groovy


static final supplier1 = ConnectionSupplier.find('5432', 'example1')
static final supplier2 = ConnectionSupplier.find('5432', 'example1')
static final supplier3 = ConnectionSupplier.find('5433', 'example1')
static final supplier4 = ConnectionSupplier.find('5433', 'example1')
    ...

def contact = new Contact(1, 'Akane', 'Apple')

//Transaktionsbeispiel
Transaction.execute(supplier1) {
    //Transaktionsstart
    new Sql<>(Contact).connection(it)
        .insert(contact)
    ...
    //Ende der Transaktion
}

Wenn während der Transaktion eine Ausnahme ausgelöst wird, wird die Methode "Transaction.rollback" ausgeführt und Andernfalls wird die Methode "Transaction.commit" ausgeführt.

Unten finden Sie ein Beschreibungsbeispiel in Java und Groovy sowie das generierte SQL. Das generierte SQL verfügt aus Gründen der Übersichtlichkeit über Zeilenumbrüche, in Wirklichkeit gibt es jedoch keine Zeilenumbrüche.

3-1. SELECT

3-1-1. SELECT 1 Zeilen- / Ausdrucksbedingung

Java


Transaction.execute(conn -> {
    Optional<Contact> contactOpt = new Sql<>(Contact.class)
        .where("{id}={}", 1)
        .connection(conn)
        .select();
});

Groovy


Transaction.execute {
    def contactOpt = new Sql<>(Contact)
        .where('{id}={}', 1)
        .connection(it)
        .select()
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE id=1

3-1-2. SELECT 1 Zeilen- / Entitätsbedingung

Java


Contact contact = new Contact();
contact.id = 1;
Transaction.execute(conn -> {
    Optional<Contact> contactOpt = new Sql<>(Contact.class)
        .where(contact)
        .connection(conn)
        .select();
});

Groovy


def contact = new Contact()
contact.id = 1
Transaction.execute {
    def contactOpt = new Sql<>(Contact)
        .where(contact)
        .connection(it)
        .select()
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE id=1

3-1-3. SELECT mehrere Zeilen / Ausdrucksbedingungen

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apple")
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apple')
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE lastName='Apple'

3-1-4. SELECT-Unterabfragebedingung

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class, "C")
        .where("EXISTS",
            new Sql<>(Phone.class, "P")
                .where("{P.contactId}={C.id}")
        )
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact, 'C')
        .where('EXISTS',
            new Sql<>(Phone, 'P')
                .where('{P.contactId}={C.id}')
        )
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT C.id C_id, C.firstName C_firstName, C.lastName C_lastName, C.birthday C_birthday,
       C.updateCount C_updateCount, C.createdTime C_createdTime, C.updatedTime C_updatedTime
  FROM Contact C
  WHERE EXISTS (SELECT * FROM Phone P WHERE P.contactId=C.id)

3-1-5. SELECT Ausdrucksbedingung / AND

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apple")
        .and  ("{firstName}={}", "Akane")
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apple')
        .and  ('{firstName}={}', 'Akane')
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE lastName='Apple' AND firstName='Akane'

3-1-6. SELECT Ausdrucksbedingung / OR

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apple")
        .or   ("{lastName}={}", "Orange")
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apple')
        .or   ('{lastName}={}', 'Orange')
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE lastName='Apple' OR lastName='Orange'

3-1-7. SELECT-Ausdrucksbedingung / (A UND B) ODER (C UND D)

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where(Condition
            .of ("{lastName}={}", "Apple")
            .and("{firstName}={}", "Akane")
        )
        .or(Condition
            .of ("{lastName}={}", "Orange")
            .and("{firstName}={}", "Setoka")
        )
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute(conn ->
    new Sql<>(Contact)
        .where(Condition
            .of ('{lastName}={}', 'Apple')
            .and('{firstName}={}', 'Akane')
        )
        .or(Condition
            .of ('{lastName}={}', 'Orange')
            .and('{firstName}={}', 'Setoka')
        )
        .connection(it)
        .select({contacts << it})
);

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE lastName='Apple' AND firstName='Akane'
    OR lastName='Orange' AND firstName='Setoka'

3-1-8. Auswahl der SELECT-Spalte

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apple")
        .columns("lastName", "firstName")
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apple')
        .columns('lastName', 'firstName')
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT firstName, lastName FROM Contact WHERE lastName='Apple'

3-1-9. SELECT GROUP BY, HAVING

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class, "C")
        .columns("lastName")
        .groupBy("{lastName}")
        .having("COUNT({lastName})>=2")
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact, 'C')
        .columns('lastName')
        .groupBy('{lastName}')
        .having('COUNT({lastName})>=2')
        .connection(it)
        .select({contacts << it})
}

SQL


SELECT MIN(C.lastName) C_lastName
  FROM Contact C
  GROUP BY C.lastName
  HAVING COUNT(C.lastName)>=2

3-1-10. SELECT ORDER BY, OFFSET, LIMIT

Java


List<Contact> contacts = new ArrayList<Contact>();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .orderBy("{lastName}")
        .orderBy("{firstName}")
        .orderBy("{id}")
        .offset(10).limit(5)
        .connection(conn)
        .select(contacts::add)
);

Groovy


List<Contact> contacts = []
Transaction.execute {
    new Sql<>(Contact)
        .orderBy('{lastName}')
        .orderBy('{firstName}')
        .orderBy('{id}')
        .offset(10).limit(5)
        .connection(it)
        .select({contacts << it})
}

SQL


-- DB2, MariaDB, MySQL, PostgreSQL, SQLite
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  ORDER BY lastName ASC, firstName ASC, id ASC
  LIMIT 5 OFFSET 10

SQL


-- Oracle, SQLServer(Zeilen beim Abrufen überspringen)
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  ORDER BY lastName ASC, firstName ASC, id ASC

3-1-11. SELECT FOR UPDATE

Java


Transaction.execute(conn -> {
    Optional<Contact> contactOpt = new Sql<>(Contact.class)
        .where("{id}={}", 1)
        .forUpdate()
        .connection(conn)
        .select();
});

Groovy


Transaction.execute {
    def contactOpt = new Sql<>(Contact)
        .where('{id}={}', 1)
        .forUpdate()
        .connection(it)
        .select()
}

SQL


-- DB2
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE id=1
  FOR UPDATE WITH RS

SQL


-- MariaDB, MySQL, Oracle, PostgreSQL, SQLite
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WHERE id=1
  FOR UPDATE

SQL


-- SQLite
--SQLite unterstützt FOR UPDATE nicht, daher wird eine UnsupportedOperationException ausgelöst.

SQL


-- SQLServer
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact
  WITH (ROWLOCK,UPDLOCK)
  WHERE id=1

3-1-12. SELECT inner join

Java


List<Contact> contacts = new ArrayList<>();
List<Phone> phones = new ArrayList<>();
Transaction.execute(conn ->
    new Sql<>(Contact.class, "C")
        .innerJoin(Phone.class, "P", "{P.contactId}={C.id}")
        .where("{C.id}={}", 1)
        .connection(conn)
        .<Phone>select(contacts::add, phones::add)
);

Groovy


List<Contact> contacts = []
List<Phone> phones = []
Transaction.execute {
    new Sql<>(Contact, 'C')
        .innerJoin(Phone, 'P', '{P.contactId}={C.id}')
        .where('{C.id}={}', 1)
        .connection(it)
        .select({contacts << it}, {phones << it})
}

SQL


SELECT C.id C_id, C.lastName C_lastName, C.firstName C_firstName, C.birthday C_birthday,
       C.updateCount C_updateCount, C.createdTime C_createdTime, C.updatedTime C_updatedTime,
       P.contactId P_contactId, P.childIndex P_childIndex, P.label P_label, P.content P_content
  FROM Contact C
  INNER JOIN Phone P ON P.contactId=C.id WHERE C.id=1

3-1-13. SELECT linke äußere Verbindung

Java


List<Contact> contacts = new ArrayList<>();
List<Phone> phones = new ArrayList<>();
Transaction.execute(conn ->
	new Sql<>(Contact.class, "C")
	    .leftJoin(Phone.class, "P", "{P.contactId}={C.id}")
	    .where("{C.lastName}={}", "Apple")
        .connection(conn)
	    .<Phone>select(contacts::add, phones::add)
);

Groovy


List<Contact> contacts = []
List<Phone> phones = []
Transaction.execute {
    new Sql<>(Contact, 'C')
        .leftJoin(Phone, 'P', '{P.contactId}={C.id}')
        .where('{C.lastName}={}', 'Apple')
        .connection(it)
        .select({contacts << it}, {phones << it})
}

SQL


SELECT C.id C_id, C.lastName C_lastName, C.firstName C_firstName, C.birthday C_birthday,
       C.updateCount C_updateCount, C.createdTime C_createdTime, C.updatedTime C_updatedTime,
       P.contactId P_contactId, P.childIndex P_childIndex, P.label P_label, P.content P_content
  FROM Contact C
  LEFT OUTER JOIN Phone P ON P.contactId=C.id
  WHERE C.lastName='Apple'

3-1-14. SELECT rechte äußere Verbindung

Java


List<Contact> contacts = new ArrayList<>();
List<Phone> phones = new ArrayList<>();
Transaction.execute(conn ->
    new Sql<>(Contact.class, "C")
        .rightJoin(Phone.class, "P", "{P.contactId}={C.id}")
        .where("{P.label}={}", "Main")
        .connection(conn)
        .<Phone>select(contacts::add, phones::add)
);

Groovy


List<Contact> contacts = []
List<Phone> phones = []
Transaction.execute {
    new Sql<>(Contact, 'C')
        .rightJoin(Phone, 'P', '{P.contactId}={C.id}')
        .where('{P.label}={}', 'Main')
        .connection(it)
        .select({contacts << it}, {phones << it})
}

SQL


--SQLite löst eine Ausnahme aus, da RIGHT OUTER JOIN nicht unterstützt wird.
SELECT C.id C_id, C.lastName C_lastName, C.firstName C_firstName, C.birthday C_birthday,
       C.updateCount C_updateCount, C.createdTime C_createdTime, C.updatedTime C_updatedTime,
       P.contactId P_contactId, P.childIndex P_childIndex, P.label P_label, P.content P_content
  FROM Contact C
  RIGHT OUTER JOIN Phone P ON P.contactId=C.id
  WHERE P.label='Main'

3-1-15. SELECT COUNT(*)

Java


int[] rowCount = new int[1];
Transaction.execute(conn ->
    count[0] = new Sql<>(Contact.class)
        .where("lastName={}", "Apple")
        .connection(conn)
        .selectCount()
);

Groovy


def rowCount = 0
Transaction.execute {
    count = new Sql<>(Contact)
        .where('lastName={}', 'Apple')
        .connection(it)
        .selectCount()
}

SQL


SELECT COUNT(*) FROM Contact WHERE lastName='Apple'

3-2. INSERT

3-2-1. 1 Zeile einfügen

Java


Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .connection(conn)
        .insert(new Contact(1, "Akane", "Apple", 2001, 1, 1))

Groovy


Transaction.execute {
    new Sql<>(Contact)
        .connection(it)
       .insert(new Contact(1, "Akane", "Apple", 2001, 1, 1))
}

SQL


-- DB2, MariaDB, MySQL, Oracle, PostgreSQL
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (1, 'Apple', 'Akane', DATE'2001-01-01', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

SQL


-- SQLite
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (1, 'Apple', 'Akane', '2001-01-01', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

SQL


-- SQLServer
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (1, 'Apple', 'Akane', CAST('2001-01-01' AS DATE), 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

3-2-2. Fügen Sie mehrere Zeilen ein

Java


Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .connection(conn)
        .insert(Arrays.asList(
            new Contact(2, "Yukari", "Apple", 2001, 1, 2),
            new Contact(3, "Azusa", "Apple", 2001, 1, 3)
        ))

Groovy


Transaction.execute {
    new Sql<>(Contact)
        .connection(it)
        .insert([
            new Contact(2, "Yukari", "Apple", 2001, 1, 2),
            new Contact(3, "Azusa", "Apple", 2001, 1, 3)
        ])
}

SQL


-- DB2, MariaDB, MySQL, Oracle, PostgreSQL
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (2, 'Apple', 'Yukari', DATE'2001-01-02', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (3, 'Apple', 'Azusa', DATE'2001-01-03', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

SQL


-- SQLite
INSERT INTO Contact (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (2, 'Apple', 'Yukari', '2001-01-02', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
INSERT INTO Contact (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (3, 'Apple', 'Azusa', '2001-01-03', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

SQL


-- SQLServer
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (2, 'Apple', 'Yukari', CAST('2001-01-02' AS DATE), 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
INSERT INTO Contact
  (id, firstName, lastName, birthday, updateCount, createdTime, updatedTime)
  VALUES
  (3, 'Apple', 'Azusa', CAST('2001-01-03' AS DATE), 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

3-3. UPDATE

3-3-1. UPDATE 1 Zeile

Java


Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{id}={}", 1)
        .connection(conn)
        .select()
        .ifPresent(contact -> {
            contact.firstName = "Akiyo";
            new Sql<>(Contact.class)
                .connection(conn)
                .update(contact);
        })
);

Groovy


Transaction.execute {
    new Sql<>(Contact)
        .where('{id}={}', 1)
        .connection(it)
        .select()
        .ifPresent {Contact contact ->
            contact.firstName = 'Akiyo'
            new Sql<>(Contact)
                .connection(it)
                .update(contact)
        }
}

SQL


-- DB2, MariaDB, MySQL, Oracle, PostgreSQL
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE id=1
UPDATE Contact SET
  lastName='Apple', firstName='Akiyo', birthday=DATE'2001-01-01',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1

SQL


-- SQLite
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE id=1
UPDATE Contact SET
  lastName='Apple', firstName='Akiyo', birthday='2001-01-01',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1

SQL


-- SQLServer
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE id=1
UPDATE Contact SET
  lastName='Apple', firstName='Akiyo', birthday=CAST('2001-01-01' AS DATE),
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1

3-3-2. UPDATE Mehrere Zeilen

Java


Transaction.execute(conn -> {
    List<Contact> contacts = new ArrayList<>();
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apple")
        .connection(conn)
        .select(contact -> {
            contact.lastName = "Apfel";
            contacts.add(contact);
        });
    new Sql<>(Contact.class)
        .connection(conn)
        .update(contacts);
});

Groovy


Transaction.execute {
    List<Contact> contacts = []
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apple')
        .connection(it)
        .select({Contact contact ->
            contact.lastName = 'Apfel'
            contacts << contact
        })
    new Sql<>(Contact)
        .connection(it)
        .update(contacts)
}

SQL


-- DB2, MariaDB, MySQL, Oracle, PostgreSQL
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE lastName='Apple'
UPDATE Contact SET
  firstName='Akiyo', lastName='Apfel', birthday=DATE'2001-01-01',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1
UPDATE Contact SET
  firstName='Yukari', lastName='Apfel', birthday=DATE'2001-01-02',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=2
UPDATE Contact SET
  firstName='Azusa', lastName='Apfel', birthday=DATE'2001-01-03',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=3

SQL


-- SQLite
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
 FROM Contact WHERE lastName='Apple'
UPDATE Contact SET
  firstName='Akiyo', lastName='Apfel', birthday='2001-01-01',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1
UPDATE Contact SET
  firstName='Yukari', lastName='Apfel', birthday='2001-01-02',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=2
UPDATE Contact SET
  firstName='Azusa', lastName='Apfel', birthday='2001-01-03',
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=3

SQL


-- SQLServer
SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE lastName='Apple'
UPDATE Contact SET
  firstName='Akiyo', lastName='Apfel', birthday=CAST('2001-01-01' AS DATE),
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=1
UPDATE Contact SET
  firstName='Yukari', lastName='Apfel', birthday=CAST('2001-01-02' AS DATE),
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=2
UPDATE Contact SET
  firstName='Azusa', lastName='Apfel', birthday=CAST('2001-01-03' AS DATE),
  updateCount=updateCount+1, updatedTime=CURRENT_TIMESTAMP
  WHERE id=3

3-3-3. UPDATE-Spezifikationsbedingung, Spaltenauswahl

Java


Contact contact = new Contact();
contact.lastName = "Pomme";
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Apfel")
        .columns("lastName")
        .connection(conn)
        .update(contact)
);

Groovy


def contact = new Contact()
contact.lastName = 'Pomme'
Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Apfel')
        .columns('lastName')
        .connection(it)
        .update(contact)
}

SQL


UPDATE Contact SET lastName='Pomme' WHERE lastName='Apfel'

3-3-4. UPDATE Alle Zeilen

Java


Contact contact = new Contact();
Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where(Condition.ALL)
        .columns("birthday")
        .connection(conn)
        .update(contact)
);

Groovy


def contact = new Contact()
Transaction.execute {
    new Sql<>(Contact)
        .where(Condition.ALL)
        .columns('birthday')
        .connection(it)
        .update(contact)
}

SQL


UPDATE Contact SET birthday=NULL

3-4. DELETE

3-4-1. 1 Zeile LÖSCHEN

Java


Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{id}={}", 1)
        .connection(conn)
        .select()
        .ifPresent(contact ->
            new Sql<>(Contact.class)
                .connection(conn)
                .delete(contact))
);

Groovy


Transaction.execute {
    new Sql<>(Contact)
        .where('{id}={}', 1)
        .connection(it)
        .select()
        .ifPresent {contact ->
            new Sql<>(Contact)
                .connection(it)
                .delete(contact)
        }
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE id=1
DELETE FROM Contact WHERE id=1

3-4-2. LÖSCHEN Mehrere Zeilen

Java


Transaction.execute(conn -> {
    List<Contact> contacts = new ArrayList<>();
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Pomme")
        .connection(conn)
        .select(contacts::add);
    new Sql<>(Contact.class)
        .connection(conn)
        .delete(contacts);
});

Groovy


Transaction.execute {
    List<Contact> contacts = []
    new Sql<>(Contact)
        .where('{lastName}={}', 'Pomme')
        .connection(it)
        .select({contacts << it})
    new Sql<>(Contact)
        .connection(it)
        .delete(contacts)
}

SQL


SELECT id, firstName, lastName, birthday, updateCount, createdTime, updatedTime
  FROM Contact WHERE lastName='Pomme'
DELETE FROM Contact WHERE id=2
DELETE FROM Contact WHERE id=3

3-4-3. Spezifikationsbedingung LÖSCHEN

Java


Transaction.execute(conn ->
    new Sql<>(Contact.class)
        .where("{lastName}={}", "Orange")
        .connection(conn)
        .delete()
);

Groovy


Transaction.execute {
    new Sql<>(Contact)
        .where('{lastName}={}', 'Orange')
        .connection(it)
        .delete()
}

SQL


DELETE FROM Contact WHERE lastName='Orange'

3-4-4. LÖSCHEN Sie alle Zeilen

Java


Transaction.execute(conn ->
    new Sql<>(Phone.class)
        .where(Condition.ALL)
        .connection(conn)
        .delete()
);

Groovy


Transaction.execute {
    new Sql<>(Phone)
        .where(Condition.ALL)
        .connection(it)
        .delete()
}

SQL


DELETE FROM Phone

Recommended Posts

Einführung in Lightsleep, eine O / R-Zuordnungsbibliothek, die nur mit Java Runtime- und JDBC-Treibern funktioniert
Flexibler Datentypkonvertierungsmechanismus der O / R-Zuordnungsbibliothek Lightsleep für Java 8
Verwenden Sie JDBC mit Java und Scala.
[Über JDBC, das Java und SQL verbindet]
Probleme und Problemumgehungen, die mit jlink in openjdk eine ungewöhnlich große Laufzeit verursachen