我在我的应用程序中使用spring和hibernate并使用spring事务.
所以我在方法和带有数据库查询方法的DAO层上有注释@transaction的服务层.
@Transactional(readOnly = false)
public void get(){
}
Run Code Online (Sandbox Code Playgroud)
问题是当我想在数据库中保存一个对象时,我必须@Transaction在DAO层方法结束时使用.为什么?
我想如果我有注释@ transaction,那么spring应该在完成服务方法时自动提交事务.
DAO层:
public BaseEntity saveEntity(BaseEntity entity) throws Exception {
try {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(entity);
session.flush();
} catch (HibernateException he) {
throw new Exception("Failed to save entity " + entity);
}
return entity;
}
Run Code Online (Sandbox Code Playgroud)
服务层:
@Transactional(readOnly = false)
public BaseEntity saveEntity(BaseEntity entity) throws Exception {
return dao.saveEntity(entity);
}
Run Code Online (Sandbox Code Playgroud)
弹簧配置:
<context:property-placeholder properties-ref="deployProperties" />
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="com" /> …Run Code Online (Sandbox Code Playgroud) 我正在使用spring依赖注入,我可以通过一些外部xml文件注入对象依赖.
我的问题是:
没有使用接口可以使用弹簧DI吗?
因为使用DI,我们希望实现一件事:
如果某个类被其他具有相同方法但定义不同的类替换,那么我们不需要在引用此类的代码中进行任何更改.
这很好,如果我使用接口,因为接口可以指向实现此接口的任何类,但如果我通过DI直接注入类对象然后没有DI的意义,因为在这种情况下,如果类被替换,我必须更改我的代码也被引用的地方.
如果出现问题,请让我纠正.
让我说我有
Class Datasource{
String url;
String user;
String database;
}
Run Code Online (Sandbox Code Playgroud)
现在我在没有DI的情况下使用它
Class Abc{
Datasource datasource = new Datasource();
}
Run Code Online (Sandbox Code Playgroud)
这有什么问题,如果我使用DI,我可以得到什么好处.
获得单身对象只是DI的目标吗?