The ORM relationship between many and one and many codes using JDBC DAO

I am writing a small training tool.
The main goal is to understand how to work with persistent data without using ORM tools.
So, there is a small database with tables:

users(id, login, password, group_id)
groups(id, name, description)
roles(id, name, description)
// for many-to-many relationship between groups and roles.
groupsroles(group_id, role_id)

So, I applied the DAO template with three objects: User, Role, Group.
The question is: what is the best way to implement relationships? How to use the same connection between UserDAO, GroupDAO, RoleDAO to use database transactions?

+3
source share
3 answers

It is easy to allow a DAO to exchange a connection, because it must be created by the service level passed to each DAO object and closed. Just pass the connection.

DAO. JOIN-, . - , .

+1

- JTA. , . , JTA.

JDBC , commit() , close() .

, , , beans (EJB beans). . EJB, , . DAO beans, .

.

@Stateless
public class MyService {

   @EJB
   private UserDAO userDAO;

   @EJB
   private GroupDAO groupDAO;

   @EJB
   private RoleDAO roleDAO;

   public void myMethod() {    
        User user = userDAO.getById(...);
        Group group = groupDAO.getByUserId(...);
        // more DAO stuff
   }
}

@Stateless
public class UserDAO {

   @Resource(mappedName="java:/myDS")
   private DataSource dataSource;

   public void getById(Long id) {
      connection = dataSource.getConnection();
      // do JDBC work on connection
   }
}
+2

, . DAO . ( ) , DAO . , DAO .

TX .

All transactions are initiated and completed at the service level. The DAO will not have any commit / rollback logic. Since the connection is distributed among all DAOs, the caller (service level) fully controls the transaction.

+1
source

All Articles