基本上,我有两个服务,每个服务都为我的项目中的每个持久对象处理方法,这些服务包含端点(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
}
}
}
我想知道我把数据库事务逻辑(开始、提交、回滚)放在哪里。
- 道层
首先,我插入了 Dao 类,但是每次查询/插入/更新我都必须打开和关闭连接,当我必须使用多个 CRUD 时,我做了几个打开/关闭连接而且它既昂贵又延迟。 示例:在一个端点请求中,我想从数据库获取一些对象并更新。两个操作和两个打开/关闭连接。
- 端点层(作为示例)
其次,我将逻辑放在端点方法上打开/关闭(如上面的示例),但他们说(我的工作同事)这不是一个好的模式,在这一层开始和提交事务不是一个好主意,然后他们建议做第三种选择。
- 服务层
将逻辑(开始/提交/回滚)放入服务层,在每个方法中,我都尝试过,但是,有些方法调用另一个方法,最后一个方法也打开和关闭连接,所以当第二个方法返回时,事务关闭.
如果缺少一些重要信息,请告诉我。
最佳答案
通常这种类型的操作在服务层中执行,因为该层提供对发送到 DAO 层和来自 DAO 层的数据进行操作的逻辑 - 也就是说,您可以将它们捆绑到同一个模块中。
评论“我尝试过,但是,某些方法调用另一个方法,最后一个方法也打开和关闭连接,因此当第二个方法返回时,事务关闭。”很有趣;我不确定你是如何管理你的联系的;但如果您的连接在事务完成之前关闭,您可能希望/需要重新访问 - 您可能需要查看 Hibernates HibernateTransactionManager
关于java - mysql事务数据库逻辑可以放在哪一层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45332683/