精华内容
下载资源
问答
  • 实体类: 在类上加上注解@EntityListeners...相关属性上使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy注解 @Data @MappedSuperclass @EntityListeners(AuditingEntityListener.class)...

    实体类:

    在类上加上注解@EntityListeners(AuditingEntityListener.class)

    相关属性上使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy注解

    @Data
    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
    public abstract class BaseEntity implements Serializable{
    
        private static final long serialVersionUID = 1L;
    
        @Id
        @TableId
        @ApiModelProperty(value = "唯一标识")
        private String id = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
    
        @ApiModelProperty(value = "创建者")
        @CreatedBy
        private String createBy;
    
        @CreatedDate
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @ApiModelProperty(value = "创建时间")
        private Date createTime;
    
        @ApiModelProperty(value = "更新者")
        @LastModifiedBy
        private String updateBy;
    
        @LastModifiedDate
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @ApiModelProperty(value = "更新时间")
        private Date updateTime;
    
        @ApiModelProperty(value = "删除标志 默认0")
        private Integer delFlag = CommonConstant.STATUS_NORMAL;
    }
    

    启动类:

    启动类使用@EnableJpaAuditing启用JPA审计,此时时间字段已经可以赋值。

    // 启用JPA审计
    @EnableJpaAuditing
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication .class, args);
        }
    }

     实现AuditorAware接口:

    自定义配置类实现AuditorAware接口,重写getCurrentAuditor方法,给CreatedBy和LastModifiedBy赋值。本代码使用的是Security安全框架,所以通过Security即可获取用户名。

    @Configuration
    public class UserAuditor implements AuditorAware<String> {
    
        @Override
        public Optional<String> getCurrentAuditor() {
    
            UserDetails user;
            try {
                user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                return Optional.ofNullable(user.getUsername());
            }catch (Exception e){
                return Optional.empty();
            }
        }
    }

     

    展开全文
  • 在spring jpa audit 中,在字段或者方法上使用注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,当进行实体插入或者更新可以自动赋值 @CreatedDate 创建时间 @CreatedBy 创建人 @...

    在spring jpa audit 中,在字段或者方法上使用注解@CreatedDate@CreatedBy@LastModifiedDate@LastModifiedBy,当进行实体插入或者更新可以自动赋值

    • @CreatedDate 创建时间

    • @CreatedBy 创建人

    • @LastModifiedDate 更新时间

    • @LastModifiedBy 更新人

    使用:

    1.定义实体类,并使用注解标注字段

    复制代码
    import lombok.Data;
    import org.springframework.data.annotation.*;
    import org.springframework.data.mongodb.core.mapping.Field;
    
    import java.time.LocalDateTime;
    
    @Data
    public class BaseEntity {
      @Id private String id;
      @Field @CreatedBy private String createUserId;
    
      @Field @LastModifiedBy private String updateUserId;
    
      @Field @CreatedDate private LocalDateTime createTime; // 创建时间
    
      @Field @LastModifiedDate private LocalDateTime updateTime; // 修改时间
    }
    复制代码

    2.添加 AuditorAware配置,设置默认用户

    复制代码
    @Configuration
    @EnableMongoAuditing(auditorAwareRef = "jpaAuditorAware")//使用mongo,也可以使用其他,如jpa(mysql)
    public class JpaAuditorAware implements AuditorAware<String> {
      @Override
      public String getCurrentAuditor() {
        return "system";
      }
    }
    复制代码

    这里是直接设置了一个默认值,正常来说,应该使用springsecurity或者shiro,从请求token中获取当前登录用户,如:

    复制代码
    public final class SecurityUtils {
    
      private SecurityUtils() {}
    
      /**
       * 根据 Authorization 获取当前登录的用户
       *
       * @return 返回用户id
       */
      public static String getCurrentUserId() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        String userId = null;
        if (authentication != null) {
          if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
            userId = springSecurityUser.getUsername();
          } else if (authentication.getPrincipal() instanceof String) {
            userId = (String) authentication.getPrincipal();
          }
        }
        return userId;
      }
    }
    
    //设置Auditor
    @Component
    public class SpringSecurityAuditorAware implements AuditorAware<String> {
    
      @Override
      public String getCurrentAuditor() {
        String userId= SecurityUtils.getCurrentUserId();
        return userId;
      }
    }
    复制代码

    3.新建 User类,继承BaseEntity

    @Data
    @Document(collection = "stu")
    public class Stu extends BaseEntity 
    { String name; String clazz; }

    4.UserRepository 继承MongoRepository,连接mongo数据库

    测试:

    @RequestMapping("/user")
      public User saveUser(String name) {
        User user = new User();
        user.setName(name);
        return userRepo.save(user);
      }

     

    发现4个字段都自动赋值了。

    但是有个问题,有些场景是这样的:

        User user = new User();
        user.setName(name);
        user.setCreateUserId("hahaha");//手动设置userId

    等执行完数据库插入后,发现createUserId的值不是hahaha,还是上面默认的system 

     

    解决方法:实现Auditable接口,通过重载来自定义这些方法

    复制代码
    @Data
    public class Base extends BaseEntity implements Auditable<String, String> { 
    
      @Override
      public String getCreatedBy() {
        return this.getCreateUserId();
      }
    
      @Override
      public void setCreatedBy(String s) {
        //如果已经设置了createUserId,则取当前设置的;否则,使用当前登录的用户id(即参数s)   下同。
        String createUserId = !StringUtils.isEmpty(getCreateUserId()) ? getCreateUserId() : s;
        setCreateUserId(createUserId);
      }
    
      @Override
      public DateTime getCreatedDate() {
        return new DateTime(
            this.getCreateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
      }
    
      @Override
      public void setCreatedDate(DateTime dateTime) {
        setCreateTime(
            Instant.ofEpochMilli(dateTime.getMillis())
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime());
      }
    
      @Override
      public String getLastModifiedBy() {
        return this.getUpdateUserId();
      }
    
      @Override
      public void setLastModifiedBy(String s) {
        String createUserId = !StringUtils.isEmpty(getUpdateUserId()) ? getUpdateUserId() : s;
        setUpdateUserId(createUserId);
      }
    
      @Override
      public DateTime getLastModifiedDate() {
        return new DateTime(
            this.getUpdateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
      }
    
      @Override
      public void setLastModifiedDate(DateTime dateTime) {
        setUpdateTime(
            Instant.ofEpochMilli(dateTime.getMillis())
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime());
      }
    
      @Override
      public boolean isNew() {
        return this.getId() == null;
      }
    }
    复制代码

     

    测试:新建实体类stu,继承Base

    @Data
    @Document(collection = "stu")
    public class Stu extends Base {
      String name;
      String clazz;
    }

    web rest类:

    复制代码
    @RequestMapping("/stu")
      public String saveStu(String name) throws JsonProcessingException {
        Stu stu = new Stu();
        stu.setName(name);
        stu.setClazz(random.nextInt() + "");
        stu.setCreateUserId(name);//自定义createUserId
        stu = stuRepo.save(stu);
        return om.writeValueAsString(stu);
      }
    复制代码

     

    转载于:https://www.cnblogs.com/Struts-pring/p/10337060.html

    展开全文
  • 在spring jpa audit 中,在字段或者方法上使用注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,当进行实体插入或者更新可以自动赋值 @CreatedDate 创建时间 @CreatedBy 创建人 @LastModified...

    在spring jpa audit 中,在字段或者方法上使用注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,当进行实体插入或者更新可以自动赋值

    @CreatedDate 创建时间

    @CreatedBy 创建人

    @LastModifiedDate 更新时间

    @LastModifiedBy 更新人

    使用:

    1.定义实体类,并使用注解标注字段

    /*
     *  Copyright 2019-2020 zds
     *
     *  Licensed under the Apache License, Version 2.0 (the "License");
     *  you may not use this file except in compliance with the License.
     *  You may obtain a copy of the License at
     *
     *  http://www.apache.org/licenses/LICENSE-2.0
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */
    package me.dszhang.base;
    
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Getter;
    import lombok.Setter;
    import me.dszhang.utils.SecurityUtils;
    import org.apache.commons.lang3.builder.ToStringBuilder;
    import org.hibernate.annotations.CreationTimestamp;
    import org.hibernate.annotations.UpdateTimestamp;
    import org.springframework.data.annotation.CreatedBy;
    import org.springframework.data.annotation.LastModifiedBy;
    import org.springframework.data.domain.Auditable;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;
    import org.springframework.format.annotation.DateTimeFormat;
    
    import javax.persistence.Column;
    import javax.persistence.EntityListeners;
    import javax.persistence.MappedSuperclass;
    import javax.persistence.Transient;
    import java.io.Serializable;
    import java.lang.reflect.Field;
    import java.sql.Timestamp;
    
    /**
     * 通用字段, is_del 根据需求自行添加
     * @author zds
     * @Date 2019年10月24日20:46:32
     */
    @Getter
    @Setter
    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    /*@JsonIgnoreProperties(value = {"createBy"},
            allowGetters =  false)*/
    public class BaseAuditable implements  Serializable  {
    
        @CreatedBy
        @Column(name = "create_by", updatable = false)
        @ApiModelProperty(value = "创建人", hidden = true)
        private String createBy;
    
        @LastModifiedBy
        @Column(name = "update_by")
        @ApiModelProperty(value = "更新人", hidden = true)
        private String updatedBy;
    
        @CreationTimestamp
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        @Column(name = "create_time", updatable = false)
        @ApiModelProperty(value = "创建时间", hidden = true)
        private Timestamp createTime;
    
        @UpdateTimestamp
        @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        @Column(name = "update_time")
        @ApiModelProperty(value = "更新时间", hidden = true)
        private Timestamp updateTime;
    
        /* 分组校验 */
        public @interface Create {}
    
        /* 分组校验 */
        public @interface Update {}
    
        @Override
        public String toString() {
            ToStringBuilder builder = new ToStringBuilder(this);
            Field[] fields = this.getClass().getDeclaredFields();
            try {
                for (Field f : fields) {
                    f.setAccessible(true);
                    builder.append(f.getName(), f.get(this)).append("\n");
                }
            } catch (Exception e) {
                builder.append("toString builder encounter an error");
            }
            return builder.toString();
        }
    }
    
    

    使用springsecurity或者shiro,从请求token中获取当前登录用户,如:

    /*
     *  Copyright 2019-2020 zds
     *
     *  Licensed under the Apache License, Version 2.0 (the "License");
     *  you may not use this file except in compliance with the License.
     *  You may obtain a copy of the License at
     *
     *  http://www.apache.org/licenses/LICENSE-2.0
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */
    package me.dszhang.config;
    
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.google.common.primitives.Bytes;
    import me.dszhang.utils.SecurityUtils;
    //import org.apache.tomcat.util.http.fileupload.IOUtils;
    import org.apache.commons.io.IOUtils;
    import org.springframework.data.domain.AuditorAware;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Optional;
    
    
    /**
     * @description  : 设置审计
     * @author  : dszhang
     * @date : 2020/7/28
     */
    @Component("auditorAware")
    public class AuditorConfig implements AuditorAware<String> {
    
    
        /**
         * 返回操作员标志信息
         *
         * @return /
         */
        @Override
        public Optional<String> getCurrentAuditor() {
            try {
                // 这里应根据实际业务情况获取具体信息 
                return Optional.of(SecurityUtils.getCurrentUsername()); 
            }catch (Exception ignored){
                ignored.printStackTrace();
            }
            // 用户定时任务,或者无Token调用的情况
            return Optional.of("System");
        }
    }
    
    

    3、设置Auditor

     package me.dszhang.base;
    import lombok.Data;
    import lombok.Getter;
    import lombok.Setter;
    import me.dszhang.utils.StringUtils;
    import org.springframework.data.domain.Auditable;
    import org.springframework.lang.Nullable;
    
    import javax.persistence.Column;
    import java.sql.Timestamp;
    import java.time.Instant;
    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.time.ZoneOffset;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.TemporalAccessor;
    import java.util.Optional;
    
    
    public class BaseEntity extends BaseAuditable
            implements Auditable<String, Object,TemporalAccessor>
    {
    
        @Override
        public Optional<String> getCreatedBy() {
            String s = this.getCreateBy() == null?"":this.getCreateBy();
            return Optional.of(s);
        }
     /**
         *自定义 @CreatedBy
         * @param s 传递过来的CreateBy(支持@RequestParam和@RequestBody)
         */
        @Override
        public void setCreatedBy(String s) {
            String createUserId = !StringUtils.isEmpty(this.getCreateBy()) ? this.getCreateBy() : s;
            this.setCreateBy(createUserId);
        }
    
        @Override
        public Optional<TemporalAccessor> getCreatedDate() {
            Timestamp timestamp = this.getCreateTime() ;
            LocalDateTime time2 =LocalDateTime.ofEpochSecond(timestamp.getTime()/1000,0, ZoneOffset.ofHours(8));
            return Optional.of(time2);
            //return null ;
        }
    
        @Override
        public void setCreatedDate(TemporalAccessor temporalAccessor) {
            LocalDateTime  localDateTime = (LocalDateTime)temporalAccessor;
            Timestamp time = Timestamp.valueOf(localDateTime.now());
            this.setCreateTime(time);
        }
    
        @Override
        public Optional<String> getLastModifiedBy() {
            String s = this.getUpdatedBy()== null?"":this.getUpdatedBy();
            return Optional.of(s);
    
        }
    
        @Override
        public void setLastModifiedBy(String s) {
            String updatedBy = !StringUtils.isEmpty(getUpdatedBy()) ? getUpdatedBy() : s;
            setUpdatedBy(updatedBy);
        }
    
        @Override
        public Optional<TemporalAccessor> getLastModifiedDate() {
           /* Timestamp timestamp = this.getUpdateTime() ;
            LocalDateTime time2 =LocalDateTime.ofEpochSecond(timestamp.getTime()/1000,0, ZoneOffset.ofHours(8));
             return Optional.of(time2);*/
            return null;
        }
    
    
        @Override
        public void setLastModifiedDate(TemporalAccessor temporalAccessor) {
            LocalDateTime  localDateTime = (LocalDateTime)temporalAccessor;
            Timestamp time = Timestamp.valueOf(localDateTime.now());
            super.setUpdateTime(time);
        }
    
        @Nullable
        @Override
        public Object getId() {return null; } ;
    
        public void setId(Object id){ };
    
        @Override
        public boolean isNew() {
            return false;
        }
    }
    

    4、新建 User类,继承BaseEntity

    /*
     *  Copyright 2019-2020 zds
     *
     *  Licensed under the Apache License, Version 2.0 (the "License");
     *  you may not use this file except in compliance with the License.
     *  You may obtain a copy of the License at
     *
     *  http://www.apache.org/licenses/LICENSE-2.0
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */
    package me.dszhang.modules.system.domain;
    
    import io.swagger.annotations.ApiModelProperty;
    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    import lombok.Setter;
    import me.dszhang.base.BaseEntity;
    import javax.persistence.*;
    import javax.validation.constraints.Email;
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotNull;
    import java.io.Serializable;
    import java.util.Date;
    import java.util.Objects;
    import java.util.Set;
    
    /**
     * @author zds
     * @date 2018-11-22
     */
    @Entity
    @Getter
    @Setter
    @Table(name="sys_user")
    @NoArgsConstructor
    public class SysUser extends BaseEntity implements Serializable {
    
        @Id
        @Column(name = "user_id")
        @NotNull(groups = Update.class)
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @ApiModelProperty(value = "ID", hidden = true)
        private Long id;
    
        @ManyToMany
        @ApiModelProperty(value = "用户角色")
        @JoinTable(name = "sys_users_roles",
                joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "user_id")},
                inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")})
        private Set<Role> roles;
    
        @ManyToMany
        @ApiModelProperty(value = "用户岗位")
        @JoinTable(name = "sys_users_jobs",
                joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "user_id")},
                inverseJoinColumns = {@JoinColumn(name = "job_id",referencedColumnName = "job_id")})
        private Set<Job> jobs;
    
        @OneToOne
        @JoinColumn(name = "dept_id")
        @ApiModelProperty(value = "用户部门")
        private Dept dept;
    
        @NotBlank
        @Column(unique = true)
        @ApiModelProperty(value = "账号")
        private String username;
    
        @NotBlank
        @ApiModelProperty(value = "姓名")
        private String nickName;
    
        @Email
        @NotBlank
        @ApiModelProperty(value = "邮箱")
        private String email;
    
        @NotBlank
        @ApiModelProperty(value = "电话号码")
        private String phone;
    
        @ApiModelProperty(value = "用户性别")
        private String gender;
    
        @ApiModelProperty(value = "头像真实名称",hidden = true)
        private String avatarName;
    
        @ApiModelProperty(value = "头像存储的路径", hidden = true)
        private String avatarPath;
    
        @ApiModelProperty(value = "密码")
        private String password;
    
        @NotNull
        @ApiModelProperty(value = "是否启用")
        private Boolean enabled;
    
        @NotNull
        @ApiModelProperty(value = "用户类型")
        private Integer type;
    
        @ApiModelProperty(value = "是否为admin账号", hidden = true)
        private Boolean isAdmin = false;
    
        @Column(name = "pwd_reset_time")
        @ApiModelProperty(value = "最后修改密码的时间", hidden = true)
        private Date pwdResetTime;
    
        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            SysUser user = (SysUser) o;
            return Objects.equals(id, user.id) &&
                    Objects.equals(username, user.username);
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(id, username);
        }
    }
    
    展开全文
  • 实体类,注意需要加上@EntityListeners(AuditingEntityListener.class)这个注解才能使@CreatedDate@LastModifiedDate生效 package com.gecko.charging.partner.entity; import ...

    实体类,注意需要加上@EntityListeners(AuditingEntityListener.class)这个注解才能使@CreatedDate@LastModifiedDate生效

    package com.gecko.charging.partner.entity;
    
    import com.gecko.charging.partner.enums.PartnerType;
    import com.gecko.charging.partner.enums.PartnerSettlementMethod;
    import com.meenoframework.common.BaseEntity;
    import lombok.AllArgsConstructor;
    import lombok.Getter;
    import lombok.NoArgsConstructor;
    import lombok.Setter;
    import org.springframework.data.annotation.CreatedBy;
    import org.springframework.data.annotation.CreatedDate;
    import org.springframework.data.annotation.LastModifiedBy;
    import org.springframework.data.annotation.LastModifiedDate;
    import org.springframework.data.jpa.domain.support.AuditingEntityListener;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EntityListeners;
    import javax.persistence.Table;
    import java.util.Date;
    
    /**
     * @description: 合作商
     * @author: Wzq
     * @create: 2020-03-02 14:25
     */
    @Entity
    @Table(name = "partner")
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @EntityListeners(AuditingEntityListener.class)
    public class Partner extends BaseEntity {
    
        // 用户id
        private Long userId;
    
        // 邮箱
        private String email;
    
        // 公司名称
        private String companyName;
    
        // 组织机构代码
        private String orgCode;
    
        //区域id
        private String areaId;
    
        //详细地址
        @Column(columnDefinition = "TEXT")
        private String address;
    
        //合作商类型
        @Column(name = "type")
        private PartnerType partnerType;
    
        //结算方式
        private PartnerSettlementMethod settlementMethod;
    
        // 营业执照
        private String businessLicense;
    
        // 小区名称
        private String areaName;
    
        // 创建时间
        @CreatedDate
        private Date createTime;
    
        // 创建id
        @CreatedBy
        private Long creatorId;
    
        // 修改人
        @LastModifiedBy
        private Long updateId;
    
        // 修改时间
        @LastModifiedDate
        private Date updateTime;
    
        // 是否删除
        private Integer isDeleted;
    
    }
    
    

    @CreatedBy@LastModifiedBy使它们生效需要配置转换类实现AuditorAware接口

    package com.gecko.charging.partner.repository.auditoraware;
    
    import com.meenoframework.common.filter.ThreadLocalClient;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.domain.AuditorAware;
    
    import java.util.Optional;
    
    /**
     * @description: 合作商创建人和修改人jpa处理
     * @author: Wzq
     * @create: 2020-03-02 14:48
     */
    @Configuration
    public class PartnerAuditorAware implements AuditorAware<Long> {
        @Override
        public Optional<Long> getCurrentAuditor() {
            //项目中获取登录用户id的方法
            Long currentLoginUserId = ThreadLocalClient.get().getId();
            if(currentLoginUserId != null){
                return Optional.of(currentLoginUserId);
            }
            return Optional.empty();
        }
    }
    
    
    

    成功!

    image.png

    关注公众号回复“书籍”就可以看大佬看得同款书籍了:
    image.png

    展开全文
  • .lastModifiedDate = lastModifiedDate; } public long getVersion () { return this .version; } public void setVersion ( final long version) { this .version = version; } }
  • 支持在字段或者方法上进行注解 @CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 下面开始使用 Application类加@EnableJpaAuditing表示开启审计。 代码: @EnableTransactionManagement @...
  • 在Spring JPA中,在实体bean的属性上加注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,可以再实体插入数据库时进行设置值,这样以来,在对普通实体类的添加、修改操作时,就不用关心创建时间、...
  • 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate 表示该字段为创建时间时间字段,在...
  • 要在Spring data mongodb 中使用@CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy 这四个注解 必须实现SpringSecurityAuditorAware 官方代码 class SpringSecurityAuditorAware implements AuditorAware<...
  • Override JPA源码中createdDate,createdBy,lastModifiedBy,lastModifiedDate场景描述 公司项目升级为SpringBoot项目,新加入框架JPA,JPA自带的功能可以自动更新createdDate,createdBy,lastModifiedBy,lastModified...
  • 在春天JPA中,支持在字段或者方法上进行注解@CreatedDate, ,@CreatedBy,@LastModifiedDate,@LastModifiedBy从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate 表示该字段为创建时间时间字段,在这...
  • 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate表示该字段为创建时间时间字段,在...
  • 我要做的是EnableMongoAuditing保存createdDate,lastModifiedDate等,同时使用MongoRepositories保存数据 .我的模特课@Component@Document(collection = "CAPPING")public class TemporaryCapping e...
  • 首先要在SpringBootApplication启动类加上注解@EnableMongoAuditing import lombok.Data; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org....
  • SpringMVC API缓存 LastModified的实现总结

    千次阅读 2018-12-05 22:52:55
    Servlet的生态中,提供了一种友好机制用来提高系统...Spring MVC也很好的继承了该机制,下面我们就学习下怎么使用LastModified。 1.handler是实现了LastModified的Servlet public class MyServlet extends HttpSe...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 23,345
精华内容 9,338
关键字:

lastmodified注解