SpringDataJpa杂记(一) Auditing相关

零) 这是干什么呢?
随意翻看spring-data-jpa (以下简称sdj)文档时发现有这个有趣的小东西,
sdj提供了几个有趣的元注释用在实体类上,作为对javax.persistence.*元注释的扩展。

  • @CreatedDate
  • @CreatedBy
  • @LastModifiedDate
  • @LastModifiedBy

有了这几个元注释以后就会在实体创建或更新的时候把操作时间或操作人一并更新到数据库里去,
这个很方便。

一) 环境
  • springframework (3.2.4.RELEASE)
  • spring-data-jpa (1.3.4.RELEASE)


<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-jpa</artifactId>
	<version>1.3.4.RELEASE</version>
	<exclusions>
		<exclusion>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
		</exclusion>
		<exclusion>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
		</exclusion>
	</exclusions>
</dependency>


二) 为要监控的实体加上EntityListener
可以使用元注释或orm.xml,两者二选其一
2.1 标注
import javax.persistence.*;
import org.springframework.data.annotation.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Entity
@EntityListeners({AuditingEntityListener.class})
public class SomeEntity {

	@Id
	private Integer id;
	
	@CreatedDate
	private Long createdDate;
	
	@CreatedBy
	private User user;
	
	@LastModifiedBy
	private User lastModeiUser;
	
	// 构造
	public SomeEntity() {
	}
	
	// getter & setter
}

2.2 xml方式
<persistence-unit-metadata>
	<persistence-unit-defaults>
		<entity-listeners>
			<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener" />
		</entity-listeners>
	</persistence-unit-defaults>
</persistence-unit-metadata>


2.3 实现org.springframework.data.domain.AuditorAware<T>, 这个接口负责从安全上下文中获取系统的用户信息。我们这里以apache-shiro作为安全框架!
import domain.User;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.data.domain.AuditorAware;

public class UserAuditorAware implements AuditorAware<User> {

	@Override
	public User getCurrentAuditor() {
		Subject subject = SecurityUtils.getSubject();
		Object object = subject.getPrincipal();
		return (User) object;
	}

}


2.4 最后配置一下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd">

	<jpa:repositories base-package="pkg.of.repository" />
	
	<bean id="userAuditorAware" class="auditor.UserAuditorAware" />
	<jpa:auditing auditor-aware-ref="userAuditorAware" />

</beans>

猜你喜欢

转载自yingzhuo.iteye.com/blog/1940111