После рассмотрения различных вариантов я Мы решили использовать AOP для установки значений в поля перед вызовом метода сохранения JpaRepository.
Однако я столкнулся с проблемой, когда эта функциональность работает нормально локально, но не работает, когда я импортирую и использую его в качестве библиотеки во внешних пакетах.
аннотация
Код: Выделить всё
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IDMaker {
int length() default 7;
}
Код: Выделить всё
/**
* Aspect for generating IDs before persisting entities.
* The ID is generated for fields annotated with @IDMaker.
* The ID consists of a timestamp and a random string.
* The length of the random string is specified in the @IDMaker annotation.
*/
@Aspect
@Component
public class IDMakerAspect {
/**
* Advice that generates an ID before persisting an entity.
* @param entity the entity to persist
* @throws IllegalAccessException if the ID field cannot be accessed
*/
@Before("execution(* *.save(..)) && args(entity)")
public void beforePersist(Object entity) throws IllegalAccessException {
generateId(entity);
}
private void generateId(Object entity) throws IllegalAccessException {
for (Field field : entity.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(IDMaker.class)) {
field.setAccessible(true);
if (field.get(entity) == null) {
IDMaker idMaker = field.getAnnotation(IDMaker.class);
String generatedId = IDMakerUtils.createTimestampedRandomID(idMaker.length());
field.set(entity, generatedId);
}
}
}
}
}
Код: Выделить всё
/**
* Utility class for generating IDs.
* The ID consists of a timestamp and a random string.
* The timestamp is in the format "yyyyMMddHHmmssSSS".
* The length of the random string is specified when calling the method.
*/
public class IDMakerUtils {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
private IDMakerUtils() {
}
/**
* Generates an ID consisting of a timestamp and a random string.
* @param length the length of the random string
* @return the generated ID
*/
public static String createTimestampedRandomID(int length) {
return LocalDateTime.now().format(formatter)
+ RandomValueUtil.createRandomString(length);
}
}
Код: Выделить всё
@Service
public class TestClassService {
@Autowired
private TestClassRepository testClassRepository;
public TestClass testClasssave() {
TestClass testClass = new TestClass();
return testClassRepository.save(testClass);
}
}
public interface TestClassRepository extends JpaRepository {
}
Код: Выделить всё
@Test
void testGenerateIDs() {
TestClass testObject = testClassService.testClasssave();
assertTrue(StringUtils.isAlphanumeric(testObject.getIdField()));
assertEquals(27, testObject.getIdField().length());
}
https://central.sonatype.com/artifact/i ... .yonggoose /IDMaker/overview
После импорта библиотеки в build.gradle я применил ее к объекту.
build.gradle
Код: Выделить всё
implementation group: 'io.github.yonggoose', name: 'IDMaker', version: '0.2.1'
Код: Выделить всё
@Entity
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Table(indexes = @Index(name = "oauth_id", columnList = "oauthId", unique = true))
public class Member extends BaseTimeEntity implements UserDetails {
@Id
@IDMaker
private String id;
@Column(nullable = false)
private String oauthId;
...
}
Код: Выделить всё
@Transactional
public void registMember(MemberRegistRequest memberRegistRequest) {
Optional memberOptional = findMemberByOAuthProviderAndEmailAndName(
translateStringToOAuthProvider(memberRegistRequest.oauthPlatform()),
memberRegistRequest.email(), memberRegistRequest.name()
);
if (memberOptional.isPresent()) {
throw new AuthException(ALREADY_EXISTS_MEMBER);
}
String encodedOauthId = passwordEncoder.encode(memberRegistRequest.oauthId());
Member member = memberRegistRequest.of(encodedOauthId);
memberRepository.save(member);
}
Код: Выделить всё
ids for this class must be manually assigned before calling save():Есть ли разница между его запуском после получить библиотеку и запустить ее локально?
и Как я могу сгенерировать значение поля, применяя аннотации, такие как GeneratedValue?
Это сводит меня с ума ...
Подробнее здесь: https://stackoverflow.com/questions/785 ... andom-valu
Мобильная версия