Using JooqTemplate requires no code generation and no XML configuration.
Add Dependency
gradle:
implementation 'net.sf.sprtool:sprtool-jooq:1.7.0'
maven:
<dependency>
<groupId>net.sf.sprtool</groupId>
<artifactId>sprtool-jooq</artifactId>
<version>1.7.0</version>
</dependency>
Inject JooqTemplate
import net.sf.sprtool.jooq.JooqTemplate;
@Autowired
private JooqTemplate jt;
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
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
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);
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
Exception Cases
- Passing a
nullMap throwsNullPointerException/IllegalArgumentException. - When the table name does not exist, an exception is thrown and the message contains the table name.
Top comments (0)