skills/tinystruct-patterns/references/database.md
Use the built-in ORM-like data layer for database operations. It provides a lightweight alternative to JPA/Hibernate using POJOs extending AbstractData and XML mapping files.
Each table is represented by:
AbstractData, provides getters/setters and setData(Row).ClassName.map.xml in resources, binding Java fields to DB columns.AbstractDataProvides CRUD methods:
append() / appendAndGetId()update()delete()findAll() / findOneById() / findOneByKey(key, value)findWith(where, params)find(SQL, params)Introspect a live database table to produce the POJO and mapping file.
application.properties:
driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/mydb
database.user=root
database.password=secret
# Interactive mode
bin/dispatcher generate
# Specify table
bin/dispatcher generate --tables users
// CREATE
User user = new User();
user.setUsername("james");
user.append();
// READ
User user = new User();
user.setId(42);
user.findOneById();
// UPDATE
user.setEmail("[email protected]");
user.update();
// DELETE
user.delete();
User user = new User();
Table results = user.findWith("username LIKE ?", new Object[]{"%jam%"});
// Fluent Condition Builder
Condition condition = new Condition();
condition.setRequestFields("id,username");
Table filtered = user.find(
condition.select("`users`").and("email LIKE ?").orderBy("id DESC"),
new Object[]{"%@example.com"}
);
User.map.xml:
<mapping>
<class name="User" table="users">
<id name="Id" column="id" increment="true" generate="false" length="11" type="int"/>
<property name="username" column="username" length="50" type="varchar"/>
<property name="email" column="email" length="100" type="varchar"/>
</class>
</mapping>
src/main/resources/.users → User). Underscored columns become camelCase fields (created_at → createdAt).setFieldAsXxx methods (e.g., setFieldAsString) in setters to sync state with the internal field map.Id (inherited from AbstractData).