简体   繁体   English

Spring Boot JPA 存储库类的字节好友运行时生成

[英]Byte Buddy Runtime generation for spring boot JPA repository classes

I am using Byte Buddy to generate JPA entities and JPA repository.我正在使用Byte Buddy生成 JPA 实体和 JPA 存储库。 I am able to generate the JPA entities but not able to proceed in generating corresponding JPA repositories.我能够生成 JPA 实体,但无法继续生成相应的 JPA 存储库。 Following is the code which represent Person entity,以下是代表 Person 实体的代码,

import javax.persistence.*;
@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    protected Person(){}

    @Override
    public String toString() {
        return String.format("Person[id=%d]",id,name);
    }
}

I am able to generate the above using Bute Buddy as follows,我可以使用 Bute Buddy 生成上述内容,如下所示,

Class<?> type = new ByteBuddy()
    .subclass(Object.class)
    .name("Person")
    .defineField("id", Integer.class, Visibility.PRIVATE)
    .defineMethod("getId", Integer.class, Visibility.PUBLIC)
    .intercept(FieldAccessor.ofBeanProperty())
    .defineMethod("setId", void.class, Visibility.PUBLIC).withParameter(Integer.class)
    .intercept(FieldAccessor.ofBeanProperty())
    .make()
    .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
    .getLoaded();

Now I would like to generate corresponding Spring boot Jpa reporitories as below,现在我想生成相应的 Spring boot Jpa 报告,如下所示,

import com.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PersonRepository extends JpaRepository <Person, Long> {

}

How to create this interface with Generic attribute.如何使用 Generic 属性创建此接口。 Also will this work (using dynamic code generation) to persist Person object?这也可以(使用动态代码生成)持久化 Person 对象吗?

You can use the TypeDescription.Generic.Builder::parameterizedType to create a generic type:您可以使用TypeDescription.Generic.Builder::parameterizedType创建泛型类型:

TypeDescription.Generic genericType = TypeDescription.Generic.Builder
   .parameterizedType(JpaRepository.class, type, Long.class)
   .build();

You can then supply this generic type to ByteBuddy::makeInterface :然后,您可以将此泛型类型提供给ByteBuddy::makeInterface

DynamicType dt = new ByteBuddy()
  .makeInterface(genericType)
  .name("com.model.Person")
  .make();

A Byte Buddy generated class cannot be distinguished from one generated by javac, therefore this should work just as expected. Byte Buddy 生成的类无法与 javac 生成的类区分开来,因此这应该按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM