DEV Community

ts5432
ts5432

Posted on

Create record using JooqTemplate

Using JooqTemplate requires no code generation and no XML configuration.

Add Dependency

gradle:

implementation 'net.sf.sprtool:sprtool-jooq:1.7.0'
Enter fullscreen mode Exit fullscreen mode

maven:

<dependency>
    <groupId>net.sf.sprtool</groupId>
    <artifactId>sprtool-jooq</artifactId>
    <version>1.7.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Inject JooqTemplate

import net.sf.sprtool.jooq.JooqTemplate;

@Autowired
private JooqTemplate jt;
Enter fullscreen mode Exit fullscreen mode

Using JooqTemplate

Inserting a Product Record

Set field values by building a Map, then call the insert method to insert a product record:

Map<String, Object> product = new HashMap<>();
product.put("name", "Phone");
product.put("price", 3999.00);
product.put("stock", 100);
product.put("category", "digital");

int result = jt.insert("product", product);
// result == 1 means the insert succeeded
Enter fullscreen mode Exit fullscreen mode

Inserting a User Record (Partial Fields)

When only some fields are set, the unset fields are written as null:

Map<String, Object> user = new HashMap<>();
user.put("name", "Jack ku");
user.put("nick_name", "As");

int result = jt.insert("user", user);
// The remaining fields (such as avatar_address, birthday) are null
Enter fullscreen mode Exit fullscreen mode

Converting a Java Bean to a Map Automatically

Use JooqMaps.toSnakeCase to automatically convert a camelCase-named Bean into a snake_case-named Map, then perform the insert:

// UserEntity has properties such as name / nickName / avatarAddress / birthday
Map<String, Object> values = JooqMaps.toSnakeCase(userEntity);
int result = jt.insert("user", values);
// To keep fields whose values are null, use JooqMaps.toSnakeCaseWithNull(userEntity);
Enter fullscreen mode Exit fullscreen mode

Inserting an Empty Map

When an empty Map is passed, a record is still inserted (each field uses its default value or null):

int result = jt.insert("order", new HashMap<>());
// result == 1; a record with all fields null was inserted
Enter fullscreen mode Exit fullscreen mode

Exception Cases

  • Passing a null Map throws NullPointerException / IllegalArgumentException.
  • When the table name does not exist, an exception is thrown and the message contains the table name.

Top comments (0)