我可以将mysql事务数据库逻辑放在哪一层?

时间:2017-07-26 16:29:33

标签: java mysql hibernate transactions google-cloud-endpoints

基本上我有两个服务,每个服务处理我项目中每个持久对象的方法,这些服务包含端点(Google)将调用以执行某些操作的方法。 我正在使用Google Could Endpoints + Mysql Cloud + Hibernate。

两个PO

@Entity
public class Device {
    ...
}

@Entity
public class User {
    ...
}

每个PO的服务

public class DeviceService {
    Device getDevice(Long devId){
        return new Dao().getById(devId, Device.class);
    }
    void allocateDevice(Long userId){
        User u = new UserService().getUser(userId);
        ... do stuff
    }
}

public class UserService {
    User getUser(Long userId){
        return new Dao().getById(userId, User.class);
    }
}

每个人的终点

public class DeviceEndpoint {
    @ApiMethod(
        name = "device.get",
        path = "device/{devId}",
        httpMethod = ApiMethod.HttpMethod.GET
    )
    Device getDevice(Long devId){
        MyEntityManager em = new MyEntityManager();
        try {
           em.getTransaction().begin();
           new DeviceService().getDevice(devId);
           em.getTransaction().commit();
        }finally {
            em.cleanup(); //custom method to rollback also
        }
        return device;
    }

    @ApiMethod(
        name = "device.allocate",
        path = "device/{userId}/allocate",
        httpMethod = ApiMethod.HttpMethod.GET
    )
    void allocateDevice(Long deviceId){
        MyEntityManager em = new MyEntityManager();
        try {
           em.getTransaction().begin();
           new DeviceService().allocateDevice(userId);
           em.getTransaction().commit();
        }finally {
            em.cleanup(); //custom method to rollback also
        }
    }
}

我想知道我把数据库事务逻辑放在哪里(开始,提交,回滚)。

  1. Dao图层
  2. 首先我插入了 Dao 类,但每次查询/插入/更新我都必须打开并关闭连接,当我不得不使用多个CRUD时,我做了几个打开/关闭连接这是昂贵和延迟。 示例:在一个端点请求中,我想从db获取一些对象并进行更新。两个操作和两个打开/关闭连接。

    1. 端点图层(例如)
    2. 其次我把逻辑打开/关闭端点方法(如上例所示),但他们说(我的同事)它不是一个好的模式,在这一层开始和提交事务不是一个好主意,然后他们建议做第三种选择。

      1. 服务层
      2. 把那个逻辑(开始/提交/回滚)放到Service层,在每个方法中,我试过但是,有些方法调用另一个,最后还打开和关闭连接,所以当第二个方法返回时,事务关闭

        请让我知道案例缺少一些重要信息。

1 个答案:

答案 0 :(得分:1)

通常这种类型的操作在服务层中执行,因为该层用于提供逻辑来操作发送到DAO层和从DAO层发送的数据 - 也就是说,您可以将这些数据捆绑到同一模块中。

评论"我试过但是,有些方法调用另一个,最后也打开和关闭连接,所以当第二个方法返回时,事务关闭了。"很有趣;我不确定你是如何管理你的联系的;但是如果在事务完成之前关闭了连接,您可能需要/需要重新访问 - 您可能希望查看Hibernates HibernateTransactionManager

Where should "@Transactional" be place Service Layer or DAO