@Transactional不使用HQL或SQL更新记录

时间:2018-01-20 11:23:42

标签: sql spring hibernate hql

我正在使用事务性注释,以便在Oracle DB中启用自动提交。

当我使用条件更新记录时,我会成功更新记录。但是当我使用HQL或SQL时,在控制台中打印查询但不执行

这是通知DAO

@Repository("SystemUserNotificationDao")
public class SystemUserNotificationDaoImpl extends AbstractDao<BigDecimal, SystemUserNotification> implements SystemUserNotificationDao {

    @Override
    public Number setNotificationsAsSeen() {
        Query query = createHqlQuery("update SystemUserNotification set seen = 1 where seen = 0");
        return (Number)query.executeUpdate();
    }

}

这是服务

Service("SystemUserNotificationService")
@Transactional
public class SystemUserNotificationServiceImpl implements SystemUserNotificationService {

    @Autowired
    SystemUserNotificationDao systemUserNotificationDao;

    @Override
    public Number setNotificationsAsSeen() {
        return systemUserNotificationDao.setNotificationsAsSeen();
    }
}

这是AbstractDao

    public abstract class AbstractDao<PK extends Serializable, T> {

    private final Class<T> persistentClass;

    @SuppressWarnings("unchecked")
    public AbstractDao() {
        this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    @Autowired
    private SessionFactory sessionFactory;

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @SuppressWarnings("unchecked")
    public T getByKey(PK key) {
        return (T) getSession().get(persistentClass, key);
    }

    public void persist(T entity) {
        getSession().persist(entity);
    }

    public void update(T entity) {
        getSession().update(entity);
    }

    public void saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
    }

    public void delete(T entity) {
        getSession().delete(entity);
    }

    protected Criteria createEntityCriteria() {
        return getSession().createCriteria(persistentClass);
    }

    protected SQLQuery createSqlQuery(String query) {
        return getSession().createSQLQuery(query);
    }

    protected Query createHqlQuery(String query) {
        return getSession().createQuery(query);
    }
}

我尝试添加transaction.begin和commit但是它给了我不支持的嵌套事务

    @Override
    public Number setNotificationsAsSeen() {
//        Query query = createHqlQuery("update SystemUserNotification set seen = 1 where seen = 0");
        Transaction tx = getSession().beginTransaction();
        Query query = getSession().createQuery("update SystemUserNotification set seen = 1 where seen = 0");
        Number n = (Number)query.executeUpdate();
        tx.commit();
        return n;
    }

1 个答案:

答案 0 :(得分:2)

问题出在SQL开发人员工具上。有未提交的更改,我关闭了开发工具,更新查询工作正常