Java 我可以将mysql事务数据库逻辑放在哪一层?
基本上,我有两个服务,每个服务处理我在项目中拥有的每个持久对象的方法,这些服务包含端点(Google)将调用以执行某些操作的方法。 我用的是谷歌可以端点+Mysql云+Hibernate 两个位置Java 我可以将mysql事务数据库逻辑放在哪一层?,java,mysql,hibernate,transactions,google-cloud-endpoints,Java,Mysql,Hibernate,Transactions,Google Cloud Endpoints,基本上,我有两个服务,每个服务处理我在项目中拥有的每个持久对象的方法,这些服务包含端点(Google)将调用以执行某些操作的方法。 我用的是谷歌可以端点+Mysql云+Hibernate 两个位置 @Entity public class Device { ... } @Entity public class User { ... } 每个POs机的服务 public class DeviceService { Device getDevice(Long devId)
@Entity
public class Device {
...
}
@Entity
public class User {
...
}
每个POs机的服务
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层和从DAO层发送的数据进行操作的逻辑,也就是说,您可以将这些数据捆绑到同一个模块中 注释“我试过了,但有些方法调用另一个,最后一个方法也打开和关闭连接,所以当第二个方法返回时,事务就关闭了。”很有趣;我不知道你是如何管理你的关系的;但是,如果您的连接在事务完成之前关闭,您可能希望/需要重新访问—您可能希望了解Hibernates HibernateTransactionManager
首先,您不能在服务层中放置任何逻辑。它应该几乎不告诉您对象实际做了什么,正如所说的:使用数据访问对象(DAO)来抽象和封装对数据源的所有访问。DAO管理与数据源的连接以获取和存储数据。您可以添加一个业务模型层,并添加我在所做的第一个选项中提到的逻辑INA,该逻辑在DAO中没有避免,例如,当我只想为一个请求在数据库中执行一些操作时,它已经打开并提交了好几次。我需要避免这种行为,因为它非常昂贵,在端点层似乎比另一层要快。我如何管理我的连接的示例,您可以在有问题的代码中看到,在端点层。如果我可以使用@Transactional annotation,那就太好了,但我不能使用Spring模块,因为我相信这个注释可以处理您在最后一个方法上尝试打开和关闭的次数。示例:两种方法都有注释,第一种方法称为第二种方法,该注释处理谁将正确打开和关闭事务,但这只是我的感觉。