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>
import javax.persistence.*;import org.springframework.data.annotation.*;import org.springframework.data.jpa.domain.support.AuditingEntityListener;@Entity@EntityListeners({AuditingEntityListener.class})public class SomeEntity {@Idprivate Integer id;@CreatedDateprivate Long createdDate;@CreatedByprivate User user;@LastModifiedByprivate User lastModeiUser;// 构造public SomeEntity() {}// getter & setter}
<persistence-unit-metadata><persistence-unit-defaults><entity-listeners><entity-listener /></entity-listeners></persistence-unit-defaults></persistence-unit-metadata>
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> {@Overridepublic User getCurrentAuditor() {Subject subject = SecurityUtils.getSubject();Object object = subject.getPrincipal();return (User) object;}}
<?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.xsdhttp://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" /><jpa:auditing auditor-aware-ref="userAuditorAware" /></beans>