最近在看jpa的时候,想起来,要是自己写一个自定义的注解作用在entity上面应该怎么使用啊。 这里要使用到了@EntityListeners 这是一个实体的监听器
看一下springdatajpa 的官网
官方文档告诉你是咋使用,现在我们来写一个监听器。
假如我们要对年龄做限制,比如狗的年龄一般不超过20岁。我们自定义一个注解用来标记在实体的属性上面
再写一个监听器
package com.ducheng.entity;
import java.lang.reflect.Field;
import javax.persistence.PrePersist;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import com.ducheng.MaxAgeValue;
@Component
public class MAxAgeListeners {
//保存之前被调用的函数
@PrePersist
public void PrePersist(Object entity) throws Exception{
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field2 : fields) {
field2.setAccessible(true);
MaxAgeValue max = field2.getAnnotation(MaxAgeValue.class);
if(!ObjectUtils.isEmpty(max)) {
Integer valueOf = Integer.valueOf(field2.get(entity).toString());
if(valueOf > max.value()) {
throw new Exception(" 超过最大限制 ");
}
}
}
}
}
这样要加入spring的bean容器管理里面 ,
@PrePersist 是说明这个注解作用的方法在保存之前使用的。这里利用了反射,获取属性的值和反射的值进行比较。大于就抛异常。
很简单的,最后的使用
写一个测试类来测试一下。
启动服务,掉一下接口
OK,完美, 在把年龄改小一些