If you want to rely on plain Hibernate API you can use a Service layer because
- It is Use case driven
- Delimit Transaction boundaries
So you can create a AccountService, for instance, like
public static path.to.HibernateUtil.getSessionFactory;
public class AccountService {
public void withdraw(Integer accountNumber, BigDecimal amount) throws Exception {
/**
* Here you set up Transaction boundaries
*/
getSessionFactory().getCurrentSession().beginTransaction();
// Some actions goes here
getSessionFactory().getCurrentSession().getTransaction().commit();
}
}
You usually need a repository when performing some action inside your Service layer. You can Think of repository as a data provider and storage. Here you can see how i implement my repository.
If you want a maintainable and readable HQL query, I advice you externalize your HQL queries in a multline and externalized xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<query name="GIFT_CARDS_WITH_BUYER">
<![CDATA[
from
GiftCard c
left join fetch
c.buyer
where
c.recipientNotificationRequested = 1
]]>
</query>
<query name="GIFT_CARDS_WITHOUT_NO_RELATIONSHIP">
<![CDATA[
from
GiftCard
]]>
</query>
</hibernate-mapping>
So inside your Swing GUI Event, you can call your service layer like
public void actionPerformed(ActionEvent event) {
// Some related Swing GUI actions goes here (retrieve User input, validate data and so on...)
accountService.withdraw(accountNumber, new BigDecimal(amount));
}
And it is not a good idea To use persistence actions inside your Entity. If you need to perform persistence related issues inside your Entity, I Think it is better you pass your repository as parameter to your Entity
public class Account {
public void doSomething(AccountRepository repository) {
// code goes here
}
}
Maybe you want to see this Thread
I advice you Take a look at Java Persistence with Hibernate book, chapter 9 (Working with objects). ATT: read carefully
UPDATE
Why is good have a service layer ?
First of all
- It is Use case driven (It draws what your app should do)
Second of all
- It delimit Transaction boundaries
Suppose here goes your Service layer
public class MyService {
public void doSomething() {
getSessionFactory().beginTransaction();
// A POJO doing some operation
// Other POJO doing other operation
// Another POJO doing another operation
getSessionFactory().getTransaction().commit();
}
}
Notice you just define one Transaction boundary instead of defining each one inside each POJO. And more, what happens whether your business rule inside your Swing GUI need to be used inside other component. Will you use a Ctrl-c + Ctrl-v ???