Database - neowu/core-ng-project GitHub Wiki
One design principle of coreng is not twisting underlying driver api but providing facility. So the general design of Database access is based on directly JDBC mapping. Allow user perceive how app interacts with DB via JDBC calls, this enables us not only precise control of performance and also adding advanced JDBC feature easier if needed.
Repository is mainly syntax sugar, helps to generate essential SQL statement via annotations.
In module, to register entity
db().repository(Entity.class);
Then in other class, it can inject Repository via
@Inject
Respository<Entity> entityRepository;
The following entity class will be assumed:
@Table(name = "customer")
public class Customer {
@PrimaryKey(autoIncrement = true)
@Column(name = "id")
public Long id;
@NotNull
@NotBlank
@Column(name = "email")
public String email;
@NotNull
@NotBlank
@Column(name = "first_name")
public String firstName;
@NotBlank
@Column(name = "last_name")
public String lastName;
@NotNull
@Column(name = "updated_time")
public LocalDateTime updatedTime;
}
To add a new record, instantiate an entity class and assign all properties and call Repository#insert method/
Customer customer = new Customer();
customer.email = request.email;
customer.firstName = request.firstName;
customer.lastName = request.lastName;
customer.updatedTime = LocalDateTime.now();
customer.id = customerRepository.insert(customer).get();
To update a record, load the entity from db
Customer customer = customerRepository.get(id).orElseThrow(() -> new NotFoundException("customer not found, id = " + id.toString()));
or instantiate an entity class and assign primary key manually
customer.id = id;
and then update it's properties accordingly:
customer.updatedTime = LocalDateTime.now();
customer.firstName = request.firstName;
if (request.lastName != null) {
customer.lastName = request.lastName;
}
customerRepository.update(customer);
To delete a record simply call Repository.delete method and provide primary key value:
customerRepository.delete(id);
core-ng supports dynamic queries through Query interface, it defines useful methods like skip(), limit(), where(), fetch() and count(), see below example:
Query<Customer> query = customerRepository.select();
query.skip(request.skip)
.limit(request.limit);
if (!Strings.isEmpty(request.email)) {
query.where("email = ?", request.email);
}
if (!Strings.isEmpty(request.firstName)) {
query.where("first_name like ?", Strings.format("{}%", request.firstName));
}
if (!Strings.isEmpty(request.lastName)) {
query.where("last_name like ?", Strings.format("{}%", request.lastName));
}
result.customers = query.fetch().stream().map(this::view).collect(Collectors.toList());
result.total = query.count();