用于数据库操作的Spring AOP操作、数据库、AOP、Spring

2023-09-04 02:25:07 作者:乐璇

我在一个Spring中工作,Hibernate项目和数据库是Oracle。我有用于持久化相关操作的DAO层。

在我的所有表中,我有create_dateupdate_date列分别表示在表中插入和更新行时的时间戳。

有一个要求,每当发生任何插入/更新操作时,我都必须更新该特定表的上述两个时间戳列。例如,如果我的DAO层有两个方法,假设m1和m2分别负责影响T1和T2表。现在,如果调用M1方法,则T1表的时间戳列将被更新。对于插入,create_date列将被更新,而对于任何更新,update_date列将被更新。

我对Spring AOP有想法,所以我想用AOP来实现上面的需求,但我不太确定是否可以用AOP来实现。

mysql数据库崩溃时事务恢复机制 Github神作 2021Java春招高级面试指南,吃透至少阿里P6 ...

如果我可以使用AOP来满足这个要求,请告诉我。如果可能,请向我提供如何实施它的输入。

推荐答案

我已经使用Spring AOP为我的应用程序中的一个模块实现了更新日期功能。 供您参考的PFB代码

希望这将有所帮助。 我想知道是否可以对变量也有切入点。我知道这在Spring的方面j实现中可能是不可能的。但是任何解决办法:p

    **
    * @author Vikas.Chowdhury
    * @version $Revision$ Last changed by $Author$ on $Date$ as $Revision$
    */
   @Aspect
   @Component
public class UpdateDateAspect
{
    @Autowired
    private ISurveyService surveyService;

    Integer surveyId = null;

    Logger gtLogger = Logger.getLogger(this.getClass().getName());

    @Pointcut("execution(* com.xyz.service.impl.*.saveSurvey*(..)))")
    public void updateDate()
    {

    }

    @Around("updateDate()")
    public Object myAspect(final ProceedingJoinPoint pjp)
    {

        // retrieve the runtime method arguments (dynamic)
        Object returnVal = null;
        for (final Object argument : pjp.getArgs())
        {

            if (argument instanceof SurveyHelper)
            {
                SurveyHelper surveyHelper = (SurveyHelper) argument;
                surveyId = surveyHelper.getSurveyId();

            }

        }
        try
        {
            returnVal = pjp.proceed();
        }
        catch (Throwable e)
        {
            gtLogger.debug("Unable to use JointPoint :(");
        }
        return returnVal;
    }

    @After("updateDate()")
    public void updateSurveyDateBySurveyId() throws Exception
    {
        if (surveyId != null)
        {
            surveyService.updateSurveyDateBySurveyId(surveyId);
        }
    }
}