精华内容
下载资源
问答
  • 实体类: 在类上加上注解@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();
            }
        }
    }

     

    展开全文
  • .lastModifiedDate = lastModifiedDate; } public long getVersion () { return this .version; } public void setVersion ( final long version) { this .version = version; } }

    1.pom.xml的文件

      <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.2.7.RELEASE</version>
        </parent>
    <dependencies>
        <dependency>
         <groupId>business-base</groupId>
        <artifactId>li-common</artifactId>
        </dependency>
         <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                 <version>5.1.38</version>
            </dependency>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-data-jpa</artifactId>
          </dependency>
      </dependencies>

    2.配置代码

    @Configuration
    @EnableJpaAuditing
    public class AuditingConfig {
    
        @Bean
        public AuditorAware<String> auditorProvider() {
            return new DefaultAuditorAwareImpl();
        }
    
    }
    public class DefaultAuditorAwareImpl implements AuditorAware<String> {
    
        @Override
        public String getCurrentAuditor() {
        //此处应该返回当前登录的用户的名,可以使用    private static final ThreadLocal<AuthContext> contextHolder = new InheritableThreadLocal<AuthContext>();等线程方法 将登录用户存入
        //
    
            return null;
        }
    
    }

    3.抽象模型类

    @MappedSuperclass
    public abstract class AbstractModel extends AbstractPersistable<Long> {
        private static final long serialVersionUID = 7205853521241442700L;
    
        // TODO 需要实现集群化的ID生成机制
    }
    @MappedSuperclass
    @EntityListeners(AuditingEntityListener.class)
    public abstract class AbstractAuditModel extends AbstractModel {
        private static final long serialVersionUID = -8388269103763562978L;
    
        @CreatedBy
        private String createdBy;
    
        @Temporal(TemporalType.TIMESTAMP)
        @CreatedDate
        private Date createdDate;
    
        @LastModifiedBy
        private String lastModifiedBy;
    
        @Temporal(TemporalType.TIMESTAMP)
        @LastModifiedDate
        private Date lastModifiedDate;
    
        @Version
        private long version;
    
        public String getCreatedBy() {
            return this.createdBy;
        }
    
        public void setCreatedBy(final String createdBy) {
            this.createdBy = createdBy;
        }
    
        public Date getCreatedDate() {
            return this.createdDate;
        }
    
        public void setCreatedDate(final Date createdDate) {
            this.createdDate = createdDate;
        }
    
        public String getLastModifiedBy() {
            return this.lastModifiedBy;
        }
    
        public void setLastModifiedBy(final String lastModifiedBy) {
            this.lastModifiedBy = lastModifiedBy;
        }
    
        public Date getLastModifiedDate() {
            return this.lastModifiedDate;
        }
    
        public void setLastModifiedDate(final Date lastModifiedDate) {
            this.lastModifiedDate = lastModifiedDate;
        }
    
        public long getVersion() {
            return this.version;
        }
    
        public void setVersion(final long version) {
            this.version = version;
        }
    }
    展开全文
  • 在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);
        }
    }
    
    展开全文
  • 在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

    展开全文
  • 实体类,注意需要加上@EntityListeners(AuditingEntityListener.class)这个注解才能使@CreatedDate@LastModifiedDate生效 package com.gecko.charging.partner.entity; import ...
  • 支持在字段或者方法上进行注解 @CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 下面开始使用 Application类加@EnableJpaAuditing表示开启审计。 代码: @EnableTransactionManagement @...
  • 首先要在SpringBootApplication启动类加上注解@EnableMongoAuditing import lombok.Data; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org....
  • 在Spring JPA中,在实体bean的属性上加注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,可以再实体插入数据库时进行设置值,这样以来,在对普通实体类的添加、修改操作时,就不用关心创建时间、...
  • 要在Spring data mongodb 中使用@CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy 这四个注解 必须实现SpringSecurityAuditorAware 官方代码 class SpringSecurityAuditorAware implements AuditorAware<...
  • 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate 表示该字段为创建时间时间字段,在...
  • 在春天JPA中,支持在字段或者方法上进行注解@CreatedDate, ,@CreatedBy,@LastModifiedDate,@LastModifiedBy从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate 表示该字段为创建时间时间字段,在这...
  • 选择 Spring Data JPA 框架开发时,常用在实体和字段上的注解有@Entity、@Id、@Column等。在表设计规范中,通常建议保留的有两个字段,一个是更新时间,一个是创建时间。Spring Data JPA 提供了相应的时间注解,只...
  • 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,从字面意思可以很清楚的了解,这几个注解的用处。 @CreatedDate表示该字段为创建时间时间字段,在...
  • SpringBoot整合JPA之Spring Data JPA @MappedSuperclass 在进行实体类的封装时,有时候几张表中可能有很多的共同属性。每次都去建立不同的类很麻烦。...1.@MappedSuperclass注解使用在父类上面,是用来标...

空空如也

空空如也

1 2 3 4 5
收藏数 87
精华内容 34
关键字:

lastmodified注解