【问题标题】:How to insert initial Data in Spring Many to Many Relationshionsip如何在 Spring 中插入初始数据 多对多关系
【发布时间】:2018-05-26 01:57:28
【问题描述】:

我的 Spring Boot 项目中有一个多对多的关系。通过声明项目中映射在一起的两个实体,一切正常。

但是,我想在最初运行应用程序时将数据插入表中,以便在表中包含一些初始数据。我在执行此操作时遇到问题。当我删除关系时,这很有效

以下是我如何使用 JPA 注释声明实体:

订阅者实体

@Entity
@Table(name="subscribers")
public class Subscriber {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long subscriber_id;

@Column(name= "firstname")
@Size(min = 3, max = 20, message = "Please enter a valid first name")
@NotEmpty(message = "First Name is required.")
public String firstname;

@Column(name= "lastname")
@Size(min = 3, max = 20, message = "Please enter a valid first name")
@NotEmpty(message = "Last Name is required.")
public String lastname;

private Set<Cluster> clusters;


@Pattern(
        regexp = "^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$",
        message = "Invalid Email address. Enter Correct Email Address"
)
@Column(name= "emailaddress")
@NotEmpty(message = "Email is required.")
public String email;

public Subscriber()
{
    super();
}

public Subscriber(String firstname, String lastname, String email,       Set<Cluster> clusters)
{
    this.firstname = firstname;
    this.lastname =  lastname;
    this.email =     email;

}

public long getSubscriberId()
{
    return subscriber_id;
}

public void setSubscriberId(long subscriber_id)
{
    this.subscriber_id = subscriber_id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname()
{
    return lastname;
}

public void setLastname(String lastname)
{
    this.lastname = lastname;
}

public String getEmail()
{
    return email;
}

public void setEmail(String email)
{
    this.email = email;
}

@ManyToMany(mappedBy = "subscribers")
public Set<Cluster> getClusters()
{
    return clusters;
}

public void setClusters (Set<Cluster> clusters)
{
    this.clusters = clusters;
}

集群实体

@Entity
public class Cluster {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long cluster_id;

@Column(name= "clustername")
@NotNull
public String clusterName;

@Column(name= "location")
public String location;

@Column(name= "apiaddress")
public String apiAddress;

@Column(name= "contact")
@NotNull
public String contact;

public Date creationDate;

public Set<Subscriber> subscribers;

public Cluster()
{

}

public Cluster(String clusterName, String location, String apiAddress, String contact, Set<Subscriber> subscribers)
{
    super();
    this.clusterName = clusterName;
    this.location =  location;
    this.apiAddress =     apiAddress;
    this.contact = contact;

}

public long getClusterId()
{
    return cluster_id;
}

public void setClusterId(long cluster_id)
{
    this.cluster_id = cluster_id;
}

public String getClusterName()
{
    return clusterName;
}

public void setClusterName (String clusterName)
{
    this.clusterName = clusterName;
}

public String getLocation()
{
    return location;
}

public void setLocation (String location)
{
    this.location = location;
}

public String getApiAddress()
{
    return apiAddress;
}

public void setApiAddress (String apiAddress)
{
    this.apiAddress = apiAddress;
}

public String getContact()
{
    return contact;
}

public void setContact (String contact)
{
    this.contact = contact;
}

public Date getCreationDate()
{
    return creationDate;
}

public void setCreationDate(Date creationDate)
{
    this.creationDate = creationDate;
}

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name="cluster_subscriber", joinColumns = @JoinColumn(name="cluster_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "subscriber_id", referencedColumnName = "id"))
public Set<Subscriber> getSubscribers()
{
    return subscribers;
}

public void setSubscribers(Set<Subscriber> subscribers)
{
    this.subscribers =subscribers;
}

}

用于添加数据的代码,它是 Spring Boot 应用程序中的入口点,这是我得到错误的地方

@SpringBootApplication
public class AiAdminApplication {

public static void main(String[] args) {
    SpringApplication.run(AiAdminApplication.class, args);
  /*ApplicationContext ctx = SpringApplication.run(AiAdminApplication.class, args);


  String [] beanNames = ctx.getBeanDefinitionNames();
    Arrays.sort(beanNames);
    for (String name: beanNames){
        System.out.println(name);
    }*/
}

@Component
public class DatabaseLoader implements CommandLineRunner {
    private final SubscriberRepository subscriberRepository;
    private final ClusterRepository clusterRepository;

    @Autowired
    public DatabaseLoader(SubscriberRepository subscriberRepository, ClusterRepository clusterRepository) {

        this.subscriberRepository = subscriberRepository;
        this.clusterRepository = clusterRepository;
    }

    public void run (String...strings) throws Exception {
        this.subscriberRepository.save(new Subscriber("Olalekan Samuel", "Ogunleye", "olalekan@aithenticate.za.com", 1));
        this.subscriberRepository.save(new Subscriber("Pieter", "Erasmus", "pieter@aithenticate.za.com", 2));
        this.subscriberRepository.save(new Subscriber("Nico", "Boss", "nicoboss@aithenticate.za.com", 3));
        this.subscriberRepository.save(new Subscriber("Felix Parfait", "Tandem", "parfait@aithenticate.za.com", 4));
        this.subscriberRepository.save(new Subscriber("Nkosinathi", "Nkosinatthi", "nathi@aithenticate.za.com", 5));
        this.subscriberRepository.save(new Subscriber("Balleng", "Balleng", "balleng@aithenticate.za.com", 6));
        this.subscriberRepository.save(new Subscriber("Nicolas", "Immelman", "nicolas@aithenticate.za.com", 7));
        this.subscriberRepository.save(new Subscriber("Nicolo", "Carzavallian", "nicolo@aithenticate.za.com", 8));
        this.subscriberRepository.save(new Subscriber("Shaun", "chang", "shaun@aithenticate.za.com", 9));
        this.subscriberRepository.save(new Subscriber("Andre", "Immelman", "ali@aithenticate.za.com", 10));
        this.subscriberRepository.save(new Subscriber("Michel", "Immelman", "michel@aithenticate.za.com", 11));

        this.clusterRepository.save(new Cluster("Aws-eu-west-1", "Ireland", "123.98.45", "Olalekan Samuel", 1));
        this.clusterRepository.save(new Cluster("Azure", "United State", "123.98.45", "Pieter Erasmus", 1));
        this.clusterRepository.save(new Cluster("Google Cloud", "United State", "123.98.45", "Nico Boss", 1));
        this.clusterRepository.save(new Cluster("herekou", "United Kingdom", "123.98.45", "Felix Parfait", 2));
        this.clusterRepository.save(new Cluster("IBM", "United State", "123.98.45", "Nkosinathi Nkosinathi", 4));
        this.clusterRepository.save(new Cluster("herekou", "United Kingdom", "123.98.45", "Balleng Immelman", 5));
        this.clusterRepository.save(new Cluster("Aws-eu-west-1", "Ireland", "123.98.45", "Nicolas Immelman", 6));
        this.clusterRepository.save(new Cluster("Azure", "United State", "123.98.45", "Nicolo Carzavallian", 6));
        this.clusterRepository.save(new Cluster("Google Cloud", "United State", "123.98.45", "Shaun Chang", 5));
        this.clusterRepository.save(new Cluster("herekou", "United Kingdom", "123.98.45", "Andre Immelman", 7));
        this.clusterRepository.save(new Cluster("IBM", "United State", "123.98.45", "Michel Immelman"));


    }
}

}

我收到一个无法应用的错误,但如果我删除映射和最后附加的 id,一切都很好。

任何有关如何在入口应用程序中插入数据的帮助将不胜感激。

提前致谢

【问题讨论】:

  • 构造函数期望一个 Set 并且您正在传递一个 int 参数,然后您继续忽略?
  • 感谢您向我指出这一点。你能告诉我哪个构造函数需要一个 Set 吗?再次感谢您
  • 集群和订阅者...甚至无法编译

标签: spring hibernate jpa spring-boot many-to-many


【解决方案1】:

创建一个实现 ApplicationListener 的类并放置您的代码。根据您的 web.xml 条目,在启动期间可能会多次调用此类。 所以插入时要小心,你可能会得到重复的数据。

public final class SystemStartUp implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
       //put startup code here
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2018-12-29
    • 2018-10-22
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    相关资源
    最近更新 更多