-->

스프링

 

 

1. AuditorAwareImpl

package com.shop.config;

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public class AuditorAwareImpl implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      String userId="";
      if (authentication!= null) {
        userId = authentication.getName();
      }
      return Optional.of(userId);
    }


}

 

 

2.AuditConfig

package com.shop.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
/** JPA의 Audiging 기능을 활성화 합니다.*/
@EnableJpaAuditing
public class AuditConfig {
  /**
   * 등록자와 수정자를 처리해주는 AuditorAware 을 빈으로 등록합니다.
   */
  @Bean
  public AuditorAware<String> auditorProvider (){
    return new AuditorAwareImpl();
  }


}

 

 

 

3.BaseTimeEntity

package com.shop.entity.base;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

/**
 * Auditing 를  적용하기 위해서 @EntityListeners 어노테이션 추가
 */
@EntityListeners(value={AuditingEntityListener.class})
@MappedSuperclass
@Getter
@Setter
public abstract class BaseTimeEntity {


  @CreatedDate
  @Column(updatable = false)
  private LocalDateTime regTime;

  @LastModifiedDate
  private LocalDateTime updateTime;



}


 

 

4.BaseEntity

package com.shop.entity.base;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@EntityListeners(value={AuditingEntityListener.class})
@MappedSuperclass
@Getter
public abstract class BaseEntity extends BaseTimeEntity{

  @CreatedBy
  @Column(updatable = false)
  private String createBy;

  @LastModifiedBy
  private String modifiedBy;

}

 

 

 

5.적용

package com.shop.entity;


import com.shop.constant.Role;
import com.shop.dto.MemberFormDto;
import com.shop.entity.base.BaseEntity;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.security.crypto.password.PasswordEncoder;

@Entity
@Table(name = "member")
@Getter
@Setter
@ToString
public class Member  extends BaseEntity {

  @Id
  @Column(name = "member_id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @Column(unique = true)
  private String email;

  private String password;

  private String address;

  @Enumerated(EnumType.STRING)
  private Role role;




  public static Member createMember(MemberFormDto memberFormDto, PasswordEncoder passwordEncoder) {
      Member member = new Member();
      member.setName(memberFormDto.getName());
      member.setEmail(memberFormDto.getEmail());
      member.setAddress(memberFormDto.getAddress());
      String password=passwordEncoder.encode(memberFormDto.getPassword());
      member.setPassword(password);
      member.setRole(Role.ROLE_USER);
      //member.setRole(Role.ROLE_ADMIN);
      return member;
  }
  
}

 

 

 

6.테스트

package com.shop.repository;

import com.shop.entity.Member;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.TestPropertySource;
import org.springframework.transaction.annotation.Transactional;

@SpringBootTest
@Transactional
@TestPropertySource(locations = "classpath:application-test.properties")
class MemberRepositoryTest {

  @Autowired
  MemberRepository memberRepository;

  @PersistenceContext
  EntityManager em;


  @Test
  @DisplayName("Auditing  테스트")
  @WithMockUser(username = "gildong", roles = "USER")
  public void audiginTest(){
    Member newMember =new Member();
    memberRepository.save(newMember);

    em.flush();
    em.clear();

    Member member = memberRepository.findById(newMember.getId()).orElseThrow(EntityNotFoundException::new);

    System.out.println("register time : "+member.getRegTime());
    System.out.println("update time : "+member.getUpdateTime());
    System.out.println("create member : "+member.getCreateBy());
    System.out.println("modify member : "+member.getModifiedBy());

  }

}

 

 

===>

register time : 2024-01-22T20:49:34.814453
update time : 2024-01-22T20:49:34.814453
create member : gildong
modify member : gildong

 

 

소스:

https://github.com/braverokmc79/jpa-shop-test2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 1  라이트

댓글 ( 0)

댓글 남기기

작성