有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Spring和JPA将一行数据同时添加到2个表中

我正在尝试为一家啤酒厂添加一个数据,其中数据需要放入两个表中,这些表与ID主键相连。我知道如何将数据放入一个表中,但我很难想出如何一次将其插入两个表中

我尝试过从名为breweries的数据库中编辑实体类。java能够同时插入纬度和经度变量,但是,它只是将数据添加到breweries表中

[Breweries table

[breweries_geocode

我的表单代码称为addBrewery。jsp

   </head>
<h3>Enter The Brewery Details!</h3>

<form:form method="POST" action="/Assignment2/breweries/addBrewery" modelAttribute="brewerie">

    <table>
        <tr> 
            <td><form:label path="id">ID</form:label></td>
            <td><form:input path="id"/></td> 
            <td style="color:red"><form:errors path="id"/> </td>
        </tr> 
        <tr>
            <td><form:label path="name">Name</form:label></td>
            <td><form:input path="name" /></td>
            <td style="color:red"><form:errors path="name"/> </td>
        </tr>

        <tr>
            <td><form:label path="address1">Address 1</form:label></td>
            <td><form:input path="address1" /></td>
            <td style="color:red"><form:errors path="address1"/> </td>
        </tr>
        <tr>
            <td><form:label path="address2">Address 2</form:label></td>
            <td><form:input path="address2"/></td>
            <td style="color:red"><form:errors path="address2"/> </td>

        </tr>
        <tr>
            <td><form:label path="city">City</form:label></td>
            <td><form:input path="city"/></td>
            <td style="color:red"><form:errors path="city"/> </td>

        </tr>
        <tr>
            <td><form:label path="state">State</form:label></td>
            <td><form:input path="state"/></td>
            <td style="color:red"><form:errors path="state"/> </td>

        </tr>
           <tr>
            <td><form:label path="code">Code</form:label></td>
            <td><form:input path="code"/></td>
            <td style="color:red"><form:errors path="code"/> </td>

        </tr>

        <tr>
            <td><form:label path="country">Country</form:label></td>
            <td><form:input path="country"/></td>
            <td style="color:red"> <form:errors path="country"/> </td>
        </tr>

        <tr>
            <td><form:label path="phone">Phone Number</form:label></td>
            <td><form:input path="phone"/></td>
            <td style="color:red"> <form:errors path="phone"/> </td>
        </tr>
              <tr>
            <td><form:label path="website">Website</form:label></td>
            <td><form:input path="website"/></td>
            <td style="color:red"><form:errors path="website"/> </td>

        </tr>
            <tr>
            <td><form:label path="image">Image</form:label></td>
            <td><form:input path="image"/></td>
            <td style="color:red"><form:errors path="image"/> </td>

        </tr>
        <tr>
            <td><form:label path="description">Description</form:label></td>
            <td><form:input path="description"/></td>
            <td style="color:red"> <form:errors path="description"/> </td>
        </tr>
        <tr>
            <td><form:label path="addUser">Add User</form:label></td>
            <td><form:input path="addUser"/></td>
            <td style="color:red"> <form:errors path="addUser"/> </td>
        </tr>

        <tr>
            <td><form:label path="creditLimit">Credit Limit</form:label></td>
            <td><form:input path="creditLimit"/></td>
            <td style="color:red"> <form:errors path="creditLimit"/> </td>
        </tr>
        <tr>
            <td><form:label path="email">Email</form:label></td>
            <td><form:input path="email"/></td>
            <td style="color:red"> <form:errors path="email"/> </td>
        </tr>
        <tr>
            <td><form:label path="latitude">Latitude</form:label></td>
            <td><form:input path="latitude"/></td>
            <td style="color:red"> <form:errors path="latitude"/> </td>
        </tr>
        <tr>
            <td><form:label path="longitude">Longitude</form:label></td>
            <td><form:input path="longitude"/></td>
            <td style="color:red"> <form:errors path="longitude"/> </td>
        </tr>

        <tr>

            <td><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</body>

来自名为Breweries的数据库的实体类的代码。java,我对它进行了编辑,以便能够使用纬度和经度数据变量,但仍然不会向这两个表中添加数据,而只是向breweries表中添加数据

@Entity
@Table(name = "breweries")
@SecondaryTable(name="breweries_geocode")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Breweries.findAll", query = "SELECT b FROM Breweries b"),
    @NamedQuery(name = "Breweries.findById", query = "SELECT b FROM Breweries b WHERE b.id = :id"),
    @NamedQuery(name = "Breweries.findByName", query = "SELECT b FROM Breweries b WHERE b.name = :name"),
    @NamedQuery(name = "Breweries.findByAddress1", query = "SELECT b FROM Breweries b WHERE b.address1 = :address1"),
    @NamedQuery(name = "Breweries.findByAddress2", query = "SELECT b FROM Breweries b WHERE b.address2 = :address2"),
    @NamedQuery(name = "Breweries.findByCity", query = "SELECT b FROM Breweries b WHERE b.city = :city"),
    @NamedQuery(name = "Breweries.findByState", query = "SELECT b FROM Breweries b WHERE b.state = :state"),
    @NamedQuery(name = "Breweries.findByCode", query = "SELECT b FROM Breweries b WHERE b.code = :code"),
    @NamedQuery(name = "Breweries.findByCountry", query = "SELECT b FROM Breweries b WHERE b.country = :country"),
    @NamedQuery(name = "Breweries.findByPhone", query = "SELECT b FROM Breweries b WHERE b.phone = :phone"),
    @NamedQuery(name = "Breweries.findByWebsite", query = "SELECT b FROM Breweries b WHERE b.website = :website"),
    @NamedQuery(name = "Breweries.findByImage", query = "SELECT b FROM Breweries b WHERE b.image = :image"),
    @NamedQuery(name = "Breweries.findByAddUser", query = "SELECT b FROM Breweries b WHERE b.addUser = :addUser"),
    @NamedQuery(name = "Breweries.findByLastMod", query = "SELECT b FROM Breweries b WHERE b.lastMod = :lastMod"),
    @NamedQuery(name = "Breweries.findByCreditLimit", query = "SELECT b FROM Breweries b WHERE b.creditLimit = :creditLimit"),
    @NamedQuery(name = "Breweries.findByEmail", query = "SELECT b FROM Breweries b WHERE b.email = :email")})
public class Breweries implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "name")
    private String name;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "address1")
    private String address1;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "address2")
    private String address2;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "city")
    private String city;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "state")
    private String state;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 25)
    @Column(name = "code")
    private String code;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "country")
    private String country;
    // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "phone")
    private String phone;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "website")
    private String website;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "image")
    private String image;
    @Basic(optional = false)
    @NotNull
    @Lob
    @Size(min = 1, max = 65535)
    @Column(name = "description")
    private String description;
    @Basic(optional = false)
    @NotNull
    @Column(name = "add_user")
    private int addUser;
    @Basic(optional = false)
    @NotNull
    @Column(name = "last_mod")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastMod;
    @Basic(optional = false)
    @NotNull
    @Column(name = "credit_limit")
    private double creditLimit;
    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "email")
    private String email;
    @Column(table = "breweries_geocode")
    private float latitude;
    @Column(table = "breweries_geocode")
    private float longitude;

    public float getLatitude() {
        return latitude;
    }

    public void setLatitude(float latitude) {
        this.latitude = latitude;
    }

    public float getLongitude() {
        return longitude;
    }

    public void setLongitude(float longitude) {
        this.longitude = longitude;
    }

    public Breweries() {
    }

    public Breweries(Integer id) {
        this.id = id;
    }

    public Breweries(Integer id, String name, String address1, String address2, String city, String state, String code, String country, String phone, String website, String image, String description, int addUser, Date lastMod, double creditLimit, String email) {
        this.id = id;
        this.name = name;
        this.address1 = address1;
        this.address2 = address2;
        this.city = city;
        this.state = state;
        this.code = code;
        this.country = country;
        this.phone = phone;
        this.website = website;
        this.image = image;
        this.description = description;
        this.addUser = addUser;
        this.lastMod = lastMod;
        this.creditLimit = creditLimit;
        this.email = email;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

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

    public int getAddUser() {
        return addUser;
    }

    public void setAddUser(int addUser) {
        this.addUser = addUser;
    }

    public Date getLastMod() {
        return lastMod;
    }

    public void setLastMod(Date lastMod) {
        this.lastMod = lastMod;
    }

    public double getCreditLimit() {
        return creditLimit;
    }

    public void setCreditLimit(double creditLimit) {
        this.creditLimit = creditLimit;
    }

    public String getEmail() {
        return email;
    }

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

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Breweries)) {
            return false;
        }
        Breweries other = (Breweries) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "lit.sd4.model.Breweries[ id=" + id + " ]";
    }

}

我的服务代码

  public void addAnBreweries(Breweries brewerie) {
    EntityManager em = DBUtil.getEMF().createEntityManager();
    EntityTransaction trans = em.getTransaction();
    try {
        trans.begin();
        em.persist(brewerie);
        trans.commit();
    } catch (Exception ex) {
        System.out.println(ex);
    } finally {
        em.close();
    }
}

我拥有的BreweriesController代码。爪哇

  @GetMapping("/add")
public ModelAndView displayBreweryAddForm() {
    return new ModelAndView("/addBrewery", "brewerie", new Breweries());
}

@PostMapping("/addBrewery")
public ModelAndView addAnBrewery(ModelMap model, @Valid @ModelAttribute("brewerie") Breweries brewerie, BindingResult result) {
    if (result.hasErrors()) {
        return new ModelAndView("/addBrewery");
    }
    service.addAnBreweries(brewerie);
    return new ModelAndView("redirect:/agent");

}

这段代码用于将一行添加到一个表中,但是我不确定如何将其更改为将一行添加到两个表中

酿酒厂地理编码。爪哇

@Entity
@Table(name = "breweries_geocode")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "BreweriesGeocode.findAll", query = "SELECT b FROM BreweriesGeocode b"),
    @NamedQuery(name = "BreweriesGeocode.findById", query = "SELECT b FROM BreweriesGeocode b WHERE b.id = :id"),
    @NamedQuery(name = "BreweriesGeocode.findByBreweryId", query = "SELECT b FROM BreweriesGeocode b WHERE b.breweryId = :breweryId"),
    @NamedQuery(name = "BreweriesGeocode.findByLatitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.latitude = :latitude"),
    @NamedQuery(name = "BreweriesGeocode.findByLongitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.longitude = :longitude")})
public class BreweriesGeocode implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Column(name = "brewery_id")
    private int breweryId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "latitude")
    private float latitude;
    @Basic(optional = false)
    @NotNull
    @Column(name = "longitude")
    private float longitude;

    public BreweriesGeocode() {
    }

    public BreweriesGeocode(Integer id) {
        this.id = id;
    }

    public BreweriesGeocode(Integer id, int breweryId, float latitude, float longitude) {
        this.id = id;
        this.breweryId = breweryId;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public Integer getId() {
        return id;
    }

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

    public int getBreweryId() {
        return breweryId;
    }

    public void setBreweryId(int breweryId) {
        this.breweryId = breweryId;
    }

    public float getLatitude() {
        return latitude;
    }

    public void setLatitude(float latitude) {
        this.latitude = latitude;
    }

    public float getLongitude() {
        return longitude;
    }

    public void setLongitude(float longitude) {
        this.longitude = longitude;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof BreweriesGeocode)) {
            return false;
        }
        BreweriesGeocode other = (BreweriesGeocode) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "brewery.src.model.BreweriesGeocode[ id=" + id + " ]";
    }

}

DBUtil。爪哇

public class DBUtil {
   private static final EntityManagerFactory EMF = 
        Persistence.createEntityManagerFactory("taste_PU");

public static EntityManagerFactory getEMF() { return EMF; }

}


共 (0) 个答案