Java JPA DAO模式不';不承诺

Java JPA DAO模式不';不承诺,java,spring,jpa,spring-transactions,Java,Spring,Jpa,Spring Transactions,我的下一个配置是“独立Java SWING应用程序”。 我有一个问题:我的服务运行没有错误,执行DAO delete方法,但不提交delete: Persistence.xml <persistence-unit name="springappPU" transaction-type="RESOURCE_LOCAL"> </persistence-unit> 我的SpringServiceLoader: @Service public class SpringServi

我的下一个配置是“独立Java SWING应用程序”。 我有一个问题:我的服务运行没有错误,执行DAO delete方法,但不提交delete:

Persistence.xml

<persistence-unit name="springappPU" transaction-type="RESOURCE_LOCAL">
</persistence-unit>
我的SpringServiceLoader:

@Service
public class SpringServiceLoader{

    @Autowired
    private CalendarService calendarService;
我的serviceInterface的方法标记为@Transactional

public interface CalendarioService {
@Transactional
    public void deleteDays();
}
服务调用dao-delete方法的实现

@Service("calendarService")
public class CalendarioServiceImpl implements CalendarioService{


@Autowired
private DaysDaoImpl daysDao;

@Override
public void deleteDays{
        daysDao.deleteById(1);
}

}
最后是Dao结构:

@Repository
public class DaysDaoImpl extends GenericDaoImpl< Days > {

public DaysDaoImpl(){
  setClazz(Days.class );
}
我还尝试了HQL查询,而不是调用基本的CRUD方法,结果出现错误:

TransactionRequiredException:执行更新/删除查询

 Query query = this.em
            .createQuery("delete from Days d where d.id.date < :fecha");
    query.setParameter("fecha", fecha);
    query.executeUpdate();
Query Query=this.em
.createQuery(“从d天删除,其中d.id.date<:fecha”);
setParameter(“fecha”,fecha);
query.executeUpdate();
如果我尝试让em事务手动开始/提交,则错误将更改为:

不允许在共享EntityManager上创建事务


谢谢

解决此问题的一个非常简单的方法是将
@Transactional
添加到main()方法。

使用

T entity = em.find(persistentClass, id);
获取实体。然后打电话

em.remove(entity);
或者将此记录缩短为一行


更新(感谢@M.Deinum)

我终于找到了解决方案。 CalendarService的接口标记为@Transactional works,问题是SpringServiceLoader和CalendarService都被定义为@Service

我已经将CalendarService重命名为@Component stereotype,它自动连接到标记为@Service stereotype的SpringServiceLoader,现在事务自动工作正常

谢谢大家的支持!
我将查看Spring数据

当您将
@Transactional
注释从接口移动到
CalendarioServiceImpl
时会发生什么?没有,我认为我在配置中有一些错误,因为@Transacional在任何类中都不起作用。我尝试将注释放在DAO和ServiceImpl中,但行为与实际调用
deleteDays
方法(或其他事务方法)的代码相同。小建议,不要用你的
GenericDao
重新发明轮子。谢谢你的回答,问题是我的main()方法类不在spring上下文中,因为它是一个SWING应用程序。?我可以将非spring管理bean的类设置为@Transactional吗?@user3179334 ohh,因此您需要将注释
@Transactional
从方法移动到
CalendarioService
,而不是服务层,而不是dao层应该是事务边界。所以不要把注释放在dao上。
@Entity
@Table(name="calendar_days")
public class Days implements java.io.Serializable {

@EmbeddedId
private DaysId id;

(....)
 Query query = this.em
            .createQuery("delete from Days d where d.id.date < :fecha");
    query.setParameter("fecha", fecha);
    query.executeUpdate();
T entity = em.find(persistentClass, id);
em.remove(entity);