Bibernate is a Java Object-Relational Mapping (ORM) framework which can help you work with a database in an object-oriented manner
Implemented features:
Annotations used by the framework:
How to use:
Fill in the application.properties file:
db.url=jdbc:postgresql://localhost:5432/customers
db.username=postgres
db.password=postgres
db.driver=org.postgresql.Driver
db.pool.size=5
# hikari or bibari
db.pool.provider=hikari
db.auto.dll=true
Create an entity like this one:
@ToString
@Setter
@Entity
@Table(name = "customer")
public class Customer {
@Id
private Integer id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
@Column(name = "created_at")
private LocalDateTime createdAt;
}
Declare some helper methods (optional step):
private static <T> T readInTx(Function<Session, T> sessionFunction) {
var session = sessionFactory.openSession();
var transactionManager = session.getTransactionManager();
try {
transactionManager.begin();
T result = sessionFunction.apply(session);
transactionManager.commit();
return result;
} catch (Exception e) {
transactionManager.rollback();
throw new TransactionalOperationException("Could not complete transaction", e);
} finally {
session.close();
}
}
private static void doInTx(Consumer<Session> sessionConsumer) {
readInTx(session -> {
sessionConsumer.accept(session);
return null;
});
}
Do your work inside transaction for example:
doInTx(session -> {
Customer customer = session.find(Customer.class, 45L);
Customer newCustomer = new Customer();
newCustomer.setFirstName("Anton");
newCustomer.setLastName("Prudyus");
newCustomer.setEmail("antonprudyus97424@gmail.com");
newCustomer.setCreatedAt(LocalDateTime.now());
session.persist(newCustomer);
log.info("Found customer: {}, ", customer);
Customer sameCustomer = session.find(Customer.class, 45L);
//should be true, 1st level cache
log.info("customer: {} is equal to customer {} : {} ", customer, sameCustomer, customer == sameCustomer);
sameCustomer.setFirstName("DIRTY_CHECK_766");
});
If you don't open the transaction, every operation is performed using autocommit mode.
Don't hesitate to help us with improving of our project. It's opensource and free to use. We're waiting for your contribution 😜