这篇文章主要介绍“Jpa怎么使用@EntityListeners实现实体对象的自动赋值”,在日常操作中,相信很多人在Jpa怎么使用@EntityListeners实现实体对象的自动赋值问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Jpa怎么使用@EntityListeners实现实体对象的自动赋值”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
官方解释:可以使用生命周期注解指定实体中的方法,这些方法在指定的生命周期事件发生时执行相应的业务逻辑。
简单来说,就是监听实体对象的增删改查操作,并对实体对象进行相应的处理。
JPA一共提供了7种注解,分别是:
@PostLoad
:实体对象查询之后
@PrePersist
: 实体对象保存之前
@PostPersist
:实体对象保存之后
@PreUpdate
:实体对象修改之前
@PostUpdate
:实体对象修改之后
@PreRemove
: 实体对象删除之前
@PostRemove
:实体对象删除之后
通常情况下,数据表中都会记录创建人、创建时间、修改人、修改时间等通用属性。如果每个实体对象都要对这些通用属性手动赋值,就会过于繁琐。
现在,使用这些生命周期注解,就可以实现对通用属性的自动赋值,或者记录相应操作日志。
数据库:mysql
项目搭建:演示项目通过Spring Boot 2.2.6构建,引入spring-boot-starter-data-jpa
-- 用户表
CREATE TABLE `acc_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(40) NOT NULL DEFAULT '' COMMENT '用户名',
`password` varchar(40) NOT NULL DEFAULT '' COMMENT '密码',
`create_by` varchar(80) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_by` varchar(80) DEFAULT NULL,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 日志表
CREATE TABLE `modify_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`action` varchar(20) NOT NULL DEFAULT '' COMMENT '操作',
`entity_name` varchar(40) NOT NULL DEFAULT '' COMMENT '实体类名',
`entity_key` varchar(20) DEFAULT NULL COMMENT '主键值',
`entity_value` varchar(400) DEFAULT NULL COMMENT '实体值',
`create_by` varchar(80) DEFAULT NULL,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
@MappedSuperclass
@Getter @Setter
@MappedSuperclass
// 指定对应监听类
@EntityListeners(CreateListener.class)
public abstract class IdMapped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String createBy;
private Date createTime;
}
@Getter @Setter
@MappedSuperclass
// 指定对应监听类
@EntityListeners(EditListener.class)
public abstract class EditMapped extends IdMapped{
private String updateBy;
private Date updateTime;
}
@Entity
@Table(name = "acc_user")
@Getter @Setter
public class UserEntity extends EditMapped {
private String username;
private String password;
}
@Entity
@Table(name = "modify_log")
@Getter @Setter
public class ModifyLogEntity extends IdMapped{
private String action;
private String entityName;
private String entityKey;
private String entityValue;
}
public class CreateListener extends BasicListener {
// 保存之前,为创建时间和创建人赋值
@PrePersist
public void prePersist(IdMapped idMapped) {
if (Objects.isNull(idMapped.getCreateTime())) {
idMapped.setCreateTime(new Date());
}
if (StringUtils.isBlank(idMapped.getCreateBy())) {
// 根据鉴权系统实现获取当前操作用户,此处只做模拟
idMapped.setCreateBy("test_create");
}
}
// 保存之后,记录变更日志
@PostPersist
public void postPersist(IdMapped idMapped) throws JsonProcessingException {
recordLog(ACTION_INSERT, idMapped);
}
}
public class EditListener extends BasicListener {
// 修改之前,为修改人和修改时间赋值
@PreUpdate
public void preUpdate(EditMapped editMapped) {
if (Objects.isNull(editMapped.getUpdateTime())) {
editMapped.setCreateTime(new Date());
}
if (StringUtils.isBlank(editMapped.getUpdateBy())) {
// 根据鉴权系统实现获取当前操作用户,此处只做模拟
editMapped.setUpdateBy("test_update");
}
}
// 修改之后,记录变更日志
@PostUpdate
public void postUpdate(EditMapped editMapped) throws JsonProcessingException {
recordLog(ACTION_UPDATE, editMapped);
}
// 删除之前,记录变更日志
@PreRemove
public void preRemove(EditMapped editMapped) throws JsonProcessingException {
recordLog(ACTION_DELETE, editMapped);
}
}
public class BasicListener implements ApplicationContextAware {
private ApplicationContext applicationContext;
protected static final String ACTION_INSERT = "insert";
protected static final String ACTION_UPDATE = "update";
protected static final String ACTION_DELETE = "delete";
// 记录变更日志
protected void recordLog(String action, IdMapped object) throws JsonProcessingException {
// 日志对象不需要再记录变更日志
if (object instanceof ModifyLogEntity) {
return;
}
ModifyLogEntity modifyLogEntity = new ModifyLogEntity();
modifyLogEntity.setAction(action);
modifyLogEntity.setEntityKey(String.valueOf(object.getId()));
modifyLogEntity.setEntityName(object.getClass().getSimpleName());
// 对象转json字符串存储
modifyLogEntity.setEntityValue(new ObjectMapper().writeValueAsString(object));
Optional.ofNullable(applicationContext.getBean(ModifyLogDao.class))
.ifPresent(modifyLogDao -> modifyLogDao.save(modifyLogEntity));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
@Repository
public interface UserDao extends JpaRepository<UserEntity, Long> {
}
@Repository
public interface ModifyLogDao extends JpaRepository<ModifyLogEntity, Long> {
}
模拟用户的创建、修改和删除操作
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
@Transactional
public void add(String userName, String password) {
UserEntity userEntity = new UserEntity();
userEntity.setUsername(userName);
userEntity.setPassword(password);
userDao.save(userEntity);
}
@Override
@Transactional
public void update(Long id, String password) {
UserEntity userEntity = userDao.findById(id).orElseThrow(() -> new RuntimeException("用户不存在"));
userEntity.setPassword(password);
userDao.save(userEntity);
}
@Override
@Transactional
public void delete(Long id) {
UserEntity userEntity = userDao.findById(id).orElseThrow(() -> new RuntimeException("用户不存在"));
userDao.delete(userEntity);
}
}
@SpringBootTest
public class SchoolApplicationTests {
@Autowired
private UserService userService;
@Test
public void testAdd() {
userService.add("test1", "123456");
}
}
@Test
public void testUpdate() {
userService.update(1L, "654321");
}
@Test
public void testRemove() {
userService.delete(1L);
}
到此,关于“Jpa怎么使用@EntityListeners实现实体对象的自动赋值”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。