Как обновить две таблицы с помощью весенней загрузки? - PullRequest
0 голосов
/ 02 октября 2018

Демо-модель

package com.example.demo.model;


import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;

@Entity(name="demomodel")
public class DemoModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @NotNull
    @Size(min=3, max=20)
    private String fname;
    private String lname;

    @Min(message="Age  should be 18 atleast ",value=18)
    private Integer age;

    @Pattern(message = "Invalid email id",regexp = "^[A-Za-z0-9+_.-]+@(.+)$")
    private String email;

    private String course;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dob;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="add_id")
    private Address address;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return lname;
    }
    public void setLname(String lname) {
        this.lname = lname;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getCourse() {
        return course;
    }
    public void setCourse(String course) {
        this.course = course;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }

}

Адрес

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @NotNull
    @Size(min=2, max=30)
    private String city;

    private String state;

    //@OneToOne(mappedBy="address",cascade = CascadeType.ALL)
    //@JoinColumn(name="id")
    @OneToOne(mappedBy="address")
    private DemoModel demo;



    public DemoModel getDemo() {
        return demo;
    }
    public void setDemo(DemoModel demo) {
        this.demo = demo;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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;
    }


}

Демо-контроллер

package com.example.demo.controller;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.demo.model.Address;
import com.example.demo.model.DemoModel;
import com.example.demo.repository.AddressRepo;
import com.example.demo.repository.DemoRepo;
import com.example.demo.service.DemoService;


//@RestController
@Controller
public class DemoController {

    private static final Logger logger = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    DemoRepo demoRepo;

    @Autowired 
    AddressRepo addRepo;

    @Autowired
    DemoService demoService;


    @RequestMapping(value="/", method=RequestMethod.GET)
    public String demoApp(DemoModel demoModel,Address address) {

        return "home";
    }

    @RequestMapping(value="/formsubmit",method=RequestMethod.POST)
    public String demoForm(@Valid DemoModel demoModel,BindingResult result, @Valid Address address,BindingResult res) {

        if(result.hasErrors()) {
            logger.warn("in first binding");
            return "home";
        }
        else if(res.hasErrors()) {
            logger.warn("in second binding");
            return "home";
        }

        else
        {
            demoModel.setAddress(address);
            demoRepo.save(demoModel);
            //addRepo.save(address);
            //mv.addObject("demoModel", demoModel);
            //addRepo.save(address);
            //mv.setViewName("redirect:/dashboard");
            return "redirect:/dashboard";
        }

    }

    @RequestMapping(value="/dashboard",method=RequestMethod.GET)
    public String dashform(Model model){
        model.addAttribute("demoModel", demoService.dashform());
        return "dashboard";
    }

    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") int id) {
        demoRepo.deleteById(id);
        return "redirect:/dashboard";
    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") int id,ModelMap modelMap,DemoModel demoModel,Address address) {
        modelMap.put("demoModel", demoService.find(id));
        return "edit";
    }

    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public String edit(@ModelAttribute("demoModel") DemoModel demoModel,@ModelAttribute("address") Address address,ModelMap modelMap) {
        DemoModel dm=demoService.find(demoModel.getId());
        dm.setFname(demoModel.getFname());
        dm.setLname(demoModel.getLname());
        dm.setCourse(demoModel.getCourse());
        dm.setEmail(demoModel.getEmail());
        dm.setAge(demoModel.getAge());
        dm.setDob(demoModel.getDob());
        //dm.setAddress(address);
        demoRepo.save(dm);
        return "edit";
    }



}

Демо-репозиторий

package com.example.demo.repository;

import org.springframework.data.repository.CrudRepository;

import com.example.demo.model.DemoModel;


public interface DemoRepo extends CrudRepository<DemoModel, Integer> {


}

Адрес-репозиторий

package com.example.demo.repository;

import org.springframework.data.repository.CrudRepository;

import com.example.demo.model.Address;


public interface AddressRepo extends CrudRepository<Address, Integer> {
}

Демо-сервис

package com.example.demo.service;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.model.DemoModel;
import com.example.demo.repository.DemoRepo;


@Service
public class DemoService{
    @Autowired
    DemoRepo demoRepo;

    private List<DemoModel> demoModels;

    public List <DemoModel> dashform(){

        demoModels=new ArrayList<DemoModel>();
        for(DemoModel demoModel:demoRepo.findAll() ) {
            demoModels.add(demoModel);
        }
        return demoModels;

    }


    public DemoModel find(int id) {
        // TODO Auto-generated method stub
        return demoRepo.findById(id).orElse(null);
    }


}

edit.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><!-- 
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="/source/styles.css" /> -->
<meta charset="ISO-8859-1">
<title>Insert title here</title>

</head>
<body>
    <h1>Data Received</h1>
    <form action="#" th:action="@{/edit}" method="post">

        <div th:object="${demoModel}" >
            <table  th:each="demoModel: ${demoModel}">

                <tr>
                    <td>Id:</td>
                    <td><input type="text" th:field="*{id}" th:placeholder="#{demoModel.id}"/></td>
                    <!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
                        name Error</td>  -->
                </tr>
                <tr>
                    <td>First Name:</td>
                    <td><input type="text" th:field="*{fname}" th:placeholder="#{demoModel.fname}"/></td>
                    <!-- <td th:if="${#fields.hasErrors('fname')}" th:errors="*{fname}">first
                        name Error</td>  -->
                </tr>
                <tr>
                    <td>Last Name:</td>
                    <td><input type="text" th:field="*{lname}" th:placeholder="#{demoModel.lname}"/></td>
                    <!-- <td th:if="${#fields.hasErrors('lname')}" th:errors="*{lname}">Last
                        name Error</td>  -->
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input type="text" th:field="*{email}" th:placeholder="#{demoModel.email}"/></td>
                    <!-- <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email
                        Error</td>  -->
                </tr>
                <tr>
                    <td>Course:</td>
                    <td><input type="text" th:field="*{course}" th:placeholder="#{demoModel.course}"/></td>
                    <!--  <td th:if="${#fields.hasErrors('course')}" th:errors="*{course}">course
                        Error</td>  -->
                </tr>
                <tr>
                    <td>DOB:</td>
                    <td><input type="date" th:field="*{dob}" th:placeholder="#{demoModel.dob}"/></td>
                     <!-- <td th:if="${#fields.hasErrors('dob')}" th:errors="*{dob}">age
                        Error</td>  -->
                </tr>
                <tr>
                    <td>Age:</td>
                    <td><input type="text" th:field="*{age}" th:placeholder="#{demoModel.age}"/></td>
                     <!-- <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">age
                        Error</td>  -->
                </tr>

            </table>
        </div>

        <div th:object="${address}">
            <table th:each="demoModel: ${demoModel}">
                <tr>
                    <td>State:</td>
                    <td><input type="text" th:field="*{state}" th:placeholder="#{demoModel.address.state}"/></td>

                </tr>

                <tr>
                    <td>City:</td>
                    <td><input type="text" th:field="*{city}" th:placeholder="#{demoModel.address.city}"/></td>

                </tr>
            </table>
        </div>  

        <button type="submit">Submit</button>
        </form>
</body>
</html>

dashboard.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<link rel="stylesheet" href="/source/styles.css" /><!-- 
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet"> -->

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><!-- 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> -->
</head>

<body>
    <h1>Data Received</h1>

    <table>
        <tr >
            <th rowspan=2>Id</th>
            <th rowspan=2>First Name</th>
            <th rowspan=2>Last Name</th>
            <th rowspan=2>Email</th>
            <th rowspan=2>Age</th>
            <th rowspan=2>Date of Birth</th>
            <th rowspan=2>Course</th>
            <th colspan=2>Address</th>
            <th rowspan=2>Action</th>
        </tr>
        <tr>
            <th>City</th>
            <th>State</th>
        </tr>
        <tr th:each="demoModel: ${demoModel}">
            <td th:text="${demoModel.id}">Id</td>
            <td th:text="${demoModel.fname}">First Name</td>
            <td th:text="${demoModel.lname}">Last Name</td>
            <td th:text="${demoModel.email}">Email</td>
            <td th:text="${demoModel.age}">Age</td>
            <td th:text="${demoModel.dob}">DOB</td>
            <td th:text="${demoModel.course}">Course</td>
            <td th:text="${demoModel.address.city}">City</td>
            <td th:text="${demoModel.address.state}">State</td>  

            <td> <a class="btn" th:href="@{/delete/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-trash"></span> </a> 
            <a class="btn" th:href="@{/edit/{id}/(id=${demoModel.id})}"> <span class="glyphicon glyphicon-edit"></span> </a>
            </td>
        </tr>
    </table>


        <h2> <a href="/">Go to form</a> </h2>



</body>

Панель инструментов enter image description here

Редактировать

enter image description here

Итак, вопрос в том, как обновить две таблицы?Когда я нажимаю на edit, он перенаправляется на страницу редактирования, где я вижу детали объекта demoModel, но детали объекта address не отображаются.Я не знаю, мешает ли эта проблема мне обновить обе таблицы, или есть другая проблема в контроллере для обновления данных.

При доступе к странице редактирования без намерения обновить детали обеих таблиц demoModelи адрес выбирается эффективно для определенного идентификатора.

Мое намерение обновить обе таблицы здесь не удалось.

Пожалуйста, эксперты просматривают все коды выше и предлагают мне лучшее решение, как я могу обновить обе сопоставленные таблицы OneToOne.

1 Ответ

0 голосов
/ 02 октября 2018

Вы не видите адрес, потому что он не загружен.

modelMap.put("demoModel", demoService.find(id));

Здесь вы передаете только DemoModel и вам также нужно загрузить Address.В вашем DemoModel должно определиться

@OneToOne(mappedBy="address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="add_id")
private Address address;

Теперь также в вашем редакторе Address должен присутствовать объект

...