Quickstart
https://scrapbox.io/files/6041d594011751001c4ca2c1.png
Install
You can get the binary from Maven Central Repository You add maven dependency or download the jar file to add build path. ! Sorm4j requires Java 17 (or above) after version 2.0.0 (Sorm4j version 1.4.16). code:pom.xml
<dependency>
<groupId>org.nkjmlab</groupId>
<artifactId>sorm4j</artifactId>
<version>2.0.2</version>
</dependency>
Create a class with public fields and default constructor matching a table name. For example:
Standard class
code:java
public class Customer {
public int id;
public String name;
public Customer() {} // Require public no arg constructor (default constructor)
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
}
Record class
code:java
@OrmRecord
public record Customer (int id, String name){}
Create an entry point:
The org.nkjmlab.sorm4j.Sorm class is the first entry point into the library. org.nkjmlab.sorm4j.Sorm holds JDBC javax.sql.DataSource and configures. You can create Sorm instance with (1) JDBC URL, username, password, or (2) DataSource instance.
code:java
// (1) H2 in-memory database with DriverManager
Sorm sorm = Sorm.create("jdbc:h2:mem:sormtest;DB_CLOSE_DELAY=-1");
//(2) H2 connection Pool
DataSouce dataSource = org.h2.jdbcx.JdbcConnectionPool.create("jdbc:h2:mem:sormtest;DB_CLOSE_DELAY=-1", "username","password");
Srom sorm = Sorm.create(dataSource);
Read/Write Table
You can use Object Relational Mapping function via org.nkjmlab.sorm4j.Sorm instance. Sorm gets a JDBC connection and executes task after that closes the connection immediately.
Reads matching rows from table:
code:java
List<Customer> list = sorm.readList(Customer.class, "select * from customer where id>?", 5);
Inserts new rows (the table name is guessed from the class name):
code:java
sorm.insert(new Customer(1, "Alice", "Tokyo"), new Customer(2, "Bob", "Tokyo"));
/yuunkjm/--.icon
Next
Binding parameters to SQL