Fluent API
Hint
This article is generated by AI translation.
Prerequisites
Before using LambdaTemplate, prepare a data source just like you would for JdbcTemplate. You can also pass an existing JdbcTemplate into the LambdaTemplate constructor to share the same database connection.
- Ensure you have object mappings for the database tables you operate on.
- Annotations are one way to configure mappings; see Object Mapping for more options and details.
1. Create an object mapping for the users table via annotations
@Table("users")
public class User {
@Column(name = "id", primary = true, keyType = KeyTypeEnum.Auto)
private Long id;
@Column("name")
private String name;
... // getters/setters omitted
}
@Tablemarks the type as an entity and sets the table name it maps to.@Columndefines the mapping between fields and columns.- In the example,
idis marked as the primary key and is auto-incremented by the database.
2. Create the builder
DataSource dataSource = ...;
LambdaTemplate lambda = new LambdaTemplate(dataSource);
// or
Connection conn = ...;
LambdaTemplate lambda = new LambdaTemplate(conn);
- Use the methods on
lambdato perform reads and writes. - By default,
LambdaTemplateusesRegistryManager.DEFAULTto manage type mappings.
How It Works
LambdaTemplate provides insert, update, delete, query, and freedom methods to operate on tables:
- insert generates and executes INSERT statements.
- update generates and executes UPDATE statements.
- delete generates and executes DELETE statements.
- query generates and executes SELECT statements.
You describe how to build SQL and arguments in code; at runtime the SQL is generated and executed through JdbcTemplate to return results.
Guide
- Insert: write data, batch for efficiency, and handle conflicts.
- Update: three update methods and how to avoid unsafe updates.
- Delete: delete data with
LambdaTemplate. - Query: query data with the constructor APIs provided by dbVisitor.
- Where builder: build rich conditions for
update,delete, andquery. - Group by: perform grouped queries.
- Order by: apply ordering to queries.
- Map APIs: Map remains a handy container alongside entity classes.
- Freedom mode: build and execute SQL with Maps even without mapped entity classes.