0
0

MyBatisでDBの共通カラムを設定する

Last updated at Posted at 2023-11-04

Aspectで値を設定する

Aspectを利用して、Mapperを実行する前にパラメータに値を設定する。
対象となるプロパティを共通仕様にして、これを拡張したものを利用すると良い。
今回は、以下のテーブル共通項目を自動で設定する仕様とする。

  • 登録者
  • 登録日時
  • 更新者
  • 更新日時
  • バージョン
MapperAspect

import java.lang.reflect.Method;
import java.util.Date;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

@Aspect
@Component
public class MapperAspect {

	@Before("execution(* jp.co.test.mapper.*Mapper.insert*(..)) || "
			+ "execution(* jp.co.test.mapper.*Mapper.update*(..))")
	public void setCommonProperty(JoinPoint jp) throws Throwable {

		// Mapperのメソッド名を取得
		MethodSignature signature = (MethodSignature) jp.getSignature();
		Method method = signature.getMethod();
		String methodName = method.getName();

		// ログインID(各フレームワークで保持しているIDを持ってくる)
		String loginId = "123456789";

		// 現在日時の取得
		Date now = new Date();

		// Mapperの第一引数(モデルオブジェクト)を取得
		Object[] args = jp.getArgs();
		Object dto = args[0];

		if (methodName.startsWith("insert")) {
			setInsertedProperty(loginId, now, dto);
			setUpdatedProperty(loginId, now, dto);
		} else if (methodName.startsWith("update")) {
			setUpdatedProperty(loginId, now, dto);
		}
	}

	private void setInsertedProperty(String loginId, Object now, Object dto) throws Throwable {
		Method setTorokushaId = ReflectionUtils.findMethod(dto.getClass(), "setTorokushaId", String.class);
		if (setTorokushaId != null) {
			setTorokushaId.invoke(dto, loginId);
		}
		Method setTorokuDatetime = ReflectionUtils.findMethod(dto.getClass(), "setTorokuDatetime", Date.class);
		if (setTorokuDatetime != null) {
			setTorokuDatetime.invoke(dto, now);
		}
		Method setVersion = ReflectionUtils.findMethod(dto.getClass(), "setVersion", Integer.class);
		if (setVersion != null) {
			setVersion.invoke(dto, 1);
		}
	}

	private void setUpdatedProperty(String loginId, Object now, Object dto) throws Throwable {
		Method setKoshinshaId = ReflectionUtils.findMethod(dto.getClass(), "setKoshinshaId", String.class);
		if (setKoshinshaId != null) {
			setKoshinshaId.invoke(dto, loginId);
		}
		Method setKoshinDatetime = ReflectionUtils.findMethod(dto.getClass(), "setKoshinDatetime", Date.class);
		if (setKoshinDatetime != null) {
			setKoshinDatetime.invoke(dto, now);
		}
	}
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0