插入具有一对多关系的Spring Boot中

huangapple 未分类评论45阅读模式
英文:

insert with one to many relation spring boot

问题

以下是翻译好的内容:

显示表单控制器

@GetMapping("/add-tour-package")
public String showAddPackageForm(Model model) {
    TourPackage tourPackage = new TourPackage();
    Itinerary itinerary = new Itinerary();
    model.addAttribute("tourPackage", tourPackage);
    model.addAttribute("itinerary", itinerary);
    return "new-tour-package";
}

插入旅游套餐

@PostMapping("/save-tour-package")
public String saveTourPackage(@ModelAttribute("tourPackage") TourPackage tourPackage, @ModelAttribute("itinerary") Itinerary itinerary) {
    // 将套餐保存到数据库
    tourPackageService.saveTourPackage(tourPackage);
    return "redirect:/";
}

动态字段的表单。注意行程是动态输入字段,因此会有多个行程。

<form th:action="@{/save-tour-package}" th:object="${tourPackage}" method="POST">
    <!-- 表单字段省略... -->
    <div class="row append-new-field">
        <!-- 动态行程字段省略... -->
    </div>
    <div class="row delete-field">
        <!-- 删除行程字段省略... -->
    </div>
    <a href="javascript:;" onclick="addItineraryFields()" class="text-success">Add Fields</a>
    <div class="form-group">
        <button type="submit" class="btn btn-info col-2"> Save Tour Package</button>
    </div>
</form>

行程模型

@Entity
@Table(name = "itinerary")
@EntityListeners(AuditingEntityListener.class)
public class Itinerary {
    // 表字段和关联省略...
}

旅游套餐模型

@Entity
@Table(name = "tour_package")
@EntityListeners(AuditingEntityListener.class)
public class TourPackage {
    // 表字段和关联省略...
}

TourPackage保存功能

@Override
public long saveTourPackage(TourPackage tourPackage) {
    this.tourPackagesRepo.save(tourPackage);
    return 0;
}

Itinerary保存功能

@Override
public long saveItinerary(Itinerary itinerary) {
    this.itineraryRepo.save(itinerary);
    return 0;
}

注意:上述代码只是翻译成中文,具体的功能和逻辑涉及到Spring Boot框架和数据库操作等,需要确保代码在适当的上下文中运行才能实现预期的功能。

英文:

What i have is single page to get all the fields with its relations data.

What i want to achieve is insert Package and then insert its related iteneraries at the same time.

How do I do this? Please comment if any thing is missing that I must add to the question.

display form controller

@GetMapping(&quot;/add-tour-package&quot;)
public String showAddPackageForm(Model model) {
    TourPackage tourPackage = new TourPackage();
    Itinerary itinerary = new Itinerary();
    model.addAttribute(&quot;tourPackage&quot;, tourPackage);
    model.addAttribute(&quot;itinerary&quot;, itinerary);
    return &quot;new-tour-package&quot;;
}

Insert Tour package

@PostMapping(&quot;/save-tour-package&quot;)
public String saveTourPackage(@ModelAttribute(&quot;tourPackage&quot;) TourPackage tourPackage, @ModelAttribute(&quot;itinerary&quot;) Itinerary itinerary) {
    // save package to database
    tourPackageService.saveTourPackage(tourPackage);
    return &quot;redirect:/&quot;;
}

form with dynamic fields. Note that itinerary is dynamic input fields so there will be multiple itinerary.

&lt;form th:action=&quot;@{/save-tour-package}&quot; th:object=&quot;${tourPackage}&quot; method=&quot;POST&quot;&gt;
        &lt;div class=&quot;form-group&quot;&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;title&quot;&gt;Title&lt;/label&gt;
                &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;title&quot; th:field=&quot;*{title}&quot; placeholder=&quot;Title&quot;&gt;
            &lt;/div&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;label for=&quot;description&quot;&gt;Description&lt;/label&gt;
                &lt;textarea class=&quot;form-control&quot; id=&quot;description&quot; th:field=&quot;*{description}&quot;
                          placeholder=&quot;Description&quot;&gt;&lt;/textarea&gt;
            &lt;/div&gt;
            &lt;div class=&quot;row&quot;&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;geography&quot;&gt;Geography&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;geography&quot; th:field=&quot;*{geography}&quot;
                               placeholder=&quot;Geography&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;location&quot;&gt;Location&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;location&quot; th:field=&quot;*{location}&quot;
                               placeholder=&quot;Location&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;difficulty&quot;&gt;Difficulty&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;difficulty&quot; th:field=&quot;*{difficulty}&quot;
                               placeholder=&quot;Difficulty&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;altitude&quot;&gt;Altitude&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;altitude&quot; th:field=&quot;*{altitude}&quot;
                               placeholder=&quot;Altitude&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;religion&quot;&gt;Religion&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;religion&quot; th:field=&quot;*{religion}&quot;
                               placeholder=&quot;Title&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;ethnic_people&quot;&gt;Ethnic People&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;ethnic_people&quot; th:field=&quot;*{ethnic_people}&quot;
                               placeholder=&quot;Ethnic People&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;accommodation&quot;&gt;Accommodation&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;accommodation&quot; th:field=&quot;*{accommodation}&quot;
                               placeholder=&quot;Title&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;transportation&quot;&gt;Transportation&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;transportation&quot; th:field=&quot;*{transportation}&quot;
                               placeholder=&quot;Transportation&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;minimum_pax&quot;&gt;Minimum Pax&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;minimum_pax&quot; th:field=&quot;*{minimum_pax}&quot;
                               placeholder=&quot;Minimum Pax&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;div class=&quot;form-group&quot;&gt;
                        &lt;label for=&quot;price&quot;&gt;Price&lt;/label&gt;
                        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;price&quot; th:field=&quot;*{price}&quot; placeholder=&quot;Price&quot;&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;

            &lt;div class=&quot;row append-new-field&quot;&gt;
                &lt;div class=&quot;col-2&quot;&gt;Day&lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;Title&lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;Description&lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;Altitude&lt;/div&gt;
                &lt;div class=&quot;col-1&quot;&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class=&quot;row delete-field&quot;&gt;
                &lt;div class=&quot;col-2&quot;&gt;
                    &lt;input type=&quot;text&quot; class=&quot;form-control&quot; th:name=&quot;${itinerary.day}&quot;&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;input type=&quot;text&quot; class=&quot;form-control&quot; th:name=&quot;${itinerary.title}&quot;&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;input type=&quot;text&quot; class=&quot;form-control&quot; th:name=&quot;${itinerary.description}&quot;&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-3&quot;&gt;
                    &lt;input type=&quot;text&quot; class=&quot;form-control&quot; th:name=&quot;${itinerary.altitude}&quot;&gt;
                &lt;/div&gt;
                &lt;div class=&quot;col-1&quot;&gt;
                    &lt;a href=&quot;javascript:;&quot; class=&quot;text-danger delete-row&quot;&gt;&lt;i class=&quot;fas fa-minus-circle&quot;&gt;&lt;/i&gt;&lt;/a&gt;
                &lt;/div&gt;
            &lt;/div&gt;

            &lt;a href=&quot;javascript:;&quot; onclick=&quot;addItineraryFields()&quot; class=&quot;text-success&quot;&gt;Add Fields&lt;/a&gt;
            &lt;div class=&quot;form-group&quot;&gt;
                &lt;button type=&quot;submit&quot; class=&quot;btn btn-info col-2&quot;&gt; Save Tour Package&lt;/button&gt;
            &lt;/div&gt;

        &lt;/div&gt;
    &lt;/form&gt;

Itinerary model

package com.pristine.travels.model;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;
import java.util.Objects;

@Entity
@Table(name = &quot;itinerary&quot;)
@EntityListeners(AuditingEntityListener.class)
public class Itinerary {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private long id;
    private String day;
    private String title;
    private String description;
    private String altitude;
    private String duration;
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date added_date;
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date update_date;

    @ManyToOne
    @JoinColumn(name=&quot;packages_id&quot;)
    private TourPackage packages;

    public Itinerary() {
    }

    public Itinerary(long id, String day, String title, String description, String altitude, String duration, Date added_date, Date update_date, TourPackage packages) {
        this.id = id;
        this.day = day;
        this.title = title;
        this.description = description;
        this.altitude = altitude;
        this.duration = duration;
        this.added_date = added_date;
        this.update_date = update_date;
        this.packages = packages;
    }

    public long getId() {
        return id;
    }

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

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getAltitude() {
        return altitude;
    }

    public void setAltitude(String altitude) {
        this.altitude = altitude;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public Date getAdded_date() {
        return added_date;
    }

    public void setAdded_date(Date added_date) {
        this.added_date = added_date;
    }

    public Date getUpdate_date() {
        return update_date;
    }

    public void setUpdate_date(Date update_date) {
        this.update_date = update_date;
    }

    public TourPackage getPackages() {
        return packages;
    }

    public void setPackages(TourPackage packages) {
        this.packages = packages;
    }

    @Override
    public String toString() {
        return &quot;Itinerary{&quot; +
                &quot;id=&quot; + id +
                &quot;, day=&#39;&quot; + day + &#39;\&#39;&#39; +
                &quot;, title=&#39;&quot; + title + &#39;\&#39;&#39; +
                &quot;, description=&#39;&quot; + description + &#39;\&#39;&#39; +
                &quot;, altitude=&#39;&quot; + altitude + &#39;\&#39;&#39; +
                &quot;, duration=&#39;&quot; + duration + &#39;\&#39;&#39; +
                &quot;, added_date=&quot; + added_date +
                &quot;, update_date=&quot; + update_date +
                &quot;, packages=&quot; + packages +
                &#39;}&#39;;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Itinerary itinerary = (Itinerary) o;
        return id == itinerary.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

Tour package model

package com.pristine.travels.model;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
import java.util.Set;

@Entity
@Table(name = &quot;tour_package&quot;)
@EntityListeners(AuditingEntityListener.class)
public class TourPackage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private long id;
    private String title;
    private String description;
    private String geography;
    private String location;
    private String difficulty;
    private String altitude;
    private String religion;
    private String ethnic_people;
    private String accommodation;
    private String transportation;
    private String minimum_pax;
    private Integer price;
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date added_date;
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date update_date;

    @OneToMany(mappedBy = &quot;packages&quot;)
    private Set&lt;Itinerary&gt; itineraries;

    public TourPackage() {
    }

    public TourPackage(long id, String title, String description, String geography, String location, String difficulty, String altitude, String religion, String ethnic_people, String accommodation, String transportation, String minimum_pax, Integer price, Date added_date, Date update_date, Set&lt;Itinerary&gt; itineraries) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.geography = geography;
        this.location = location;
        this.difficulty = difficulty;
        this.altitude = altitude;
        this.religion = religion;
        this.ethnic_people = ethnic_people;
        this.accommodation = accommodation;
        this.transportation = transportation;
        this.minimum_pax = minimum_pax;
        this.price = price;
        this.added_date = added_date;
        this.update_date = update_date;
        this.itineraries = itineraries;
    }

    public long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getGeography() {
        return geography;
    }

    public void setGeography(String geography) {
        this.geography = geography;
    }

    public String getLocation() {
        return location;
    }

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

    public String getDifficulty() {
        return difficulty;
    }

    public void setDifficulty(String difficulty) {
        this.difficulty = difficulty;
    }

    public String getAltitude() {
        return altitude;
    }

    public void setAltitude(String altitude) {
        this.altitude = altitude;
    }

    public String getReligion() {
        return religion;
    }

    public void setReligion(String religion) {
        this.religion = religion;
    }

    public String getEthnic_people() {
        return ethnic_people;
    }

    public void setEthnic_people(String ethnic_people) {
        this.ethnic_people = ethnic_people;
    }

    public String getAccommodation() {
        return accommodation;
    }

    public void setAccommodation(String accommodation) {
        this.accommodation = accommodation;
    }

    public String getTransportation() {
        return transportation;
    }

    public void setTransportation(String transportation) {
        this.transportation = transportation;
    }

    public String getMinimum_pax() {
        return minimum_pax;
    }

    public void setMinimum_pax(String minimum_pax) {
        this.minimum_pax = minimum_pax;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Date getAdded_date() {
        return added_date;
    }

    public void setAdded_date(Date added_date) {
        this.added_date = added_date;
    }

    public Date getUpdate_date() {
        return update_date;
    }

    public void setUpdate_date(Date update_date) {
        this.update_date = update_date;
    }

    public Set&lt;Itinerary&gt; getItineraries() {
        return itineraries;
    }

    public void setItineraries(Set&lt;Itinerary&gt; itineraries) {
        this.itineraries = itineraries;
    }

    @Override
    public String toString() {
        return &quot;TourPackage{&quot; +
                &quot;id=&quot; + id +
                &quot;, title=&#39;&quot; + title + &#39;\&#39;&#39; +
                &quot;, description=&quot; + description +
                &quot;, geography=&#39;&quot; + geography + &#39;\&#39;&#39; +
                &quot;, location=&#39;&quot; + location + &#39;\&#39;&#39; +
                &quot;, difficulty=&#39;&quot; + difficulty + &#39;\&#39;&#39; +
                &quot;, altitude=&#39;&quot; + altitude + &#39;\&#39;&#39; +
                &quot;, religion=&#39;&quot; + religion + &#39;\&#39;&#39; +
                &quot;, ethnic_people=&#39;&quot; + ethnic_people + &#39;\&#39;&#39; +
                &quot;, accommodation=&#39;&quot; + accommodation + &#39;\&#39;&#39; +
                &quot;, transportation=&#39;&quot; + transportation + &#39;\&#39;&#39; +
                &quot;, minimum_pax=&#39;&quot; + minimum_pax + &#39;\&#39;&#39; +
                &quot;, price=&quot; + price +
                &quot;, added_date=&quot; + added_date +
                &quot;, update_date=&quot; + update_date +
                &quot;, itineraries=&quot; + itineraries +
                &#39;}&#39;;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TourPackage that = (TourPackage) o;
        return id == that.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

UPDATE

TourPackage save function

@Override
public long saveTourPackage(TourPackage tourPackage) {
    this.tourPackagesRepo.save(tourPackage);
    return 0;
}

Itinerary save function

@Override
public long saveItinerary(Itinerary itinerary) {
    this.itineraryRepo.save(itinerary);
    return 0;
}

答案1

得分: 0

在执行 tourPackageService.saveTourPackage(tourPackage); 之前,先为该 tourPackage 设置行程:tourPackage.setItineraries(itinerary);。确保对于行程也进行相同的操作(在 tourPackage.setItineraries(itinerary); 之前):

itinerary.forEach(item -> { item.setTourPackage(tourPackage); }

然后执行 tourPackageService.saveTourPackage(tourPackage);

英文:

Before doing tourPackageService.saveTourPackage(tourPackage); just set Itineraries for that tourPackage: tourPackage.setItineraries(itinerary);. Make sure you do the same for Itineraries (before tourPackage.setItineraries(itinerary);):

> itinerary.forEach(item -> { item.setTourPackage(tourPackage); }

then do tourPackageService.saveTourPackage(tourPackage);

huangapple
  • 本文由 发表于 2020年7月26日 17:43:24
  • 转载请务必保留本文链接:https://java.coder-hub.com/63098493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定