Сохранение данных из одной таблицы в другой

259
01 мая 2018, 02:29

Есть два класса Category и Type. И две таблицы в MySQL с такими же названиями.

CREATE TABLE `type` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`sort` varchar(255) NOT NULL,
`categoryid` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `category_idx` (`categoryid`),
CONSTRAINT `category` FOREIGN KEY (`categoryid`) REFERENCES 
`category_production` (`categoryid`) ON DELETE NO ACTION ON UPDATE NO ACTION
)
CREATE TABLE `category_production` (
`categoryid` int(11) NOT NULL AUTO_INCREMENT,
`category` varchar(45) NOT NULL,
PRIMARY KEY (`categoryid`)
)

При создании записи в Type есть выпадающем списку с данными из Category. Когда нажимаю кнопку для подтверждения создания записи выдает ошибку(так же и с изменением): HTTP Status 400 – Bad Request

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Если везде убираю category, то программа работает исправно.

Type.java

@Entity
@Table(name = "type")
public class Type{
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "sort")
private String sort;
@OneToOne
@JoinColumn(name = "categoryid")
private Category category;
 //геттеры и сеттеры
}

Category.java

@Entity
@Table(name = "category_production")
public class Category implements Serializable {
@Id
@Column(name = "categoryid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int  categoryid;
@Column(name = "category")
private String name_category;
//геттеры и сеттеры
}

TypeController.java

 @Controller 
 public class TypeController {
 private TypeService typeService;
 @Autowired
 @Qualifier(value = "typeService")
 public void setTypeService(TypeService typeService) {
    this.typeService = typeService;
 }
 private CategoryService categoryService;
 @Autowired
 @Qualifier(value = "categoryService")
 public void setCategoryService(CategoryService categoryService) {
    this.categoryService = categoryService;
 }
 @RequestMapping(value = "types", method = RequestMethod.GET)
 public String listType(Model model){
    model.addAttribute("type", new Type());
    model.addAttribute("listType", this.typeService.listType());
    model.addAttribute("category", new Category());
    model.addAttribute("listCategory", this.categoryService.listCategory());
    return "types";
 }
    @RequestMapping(value = "/types/add", method = RequestMethod.POST)
    public String addType(@ModelAttribute("type") Type type, 
    @ModelAttribute("category") Category category){
        if (type.getId()==0){
           this.typeService.addType(type);
    //    this.categoryService.addCategory(category);
        }else {
            this.typeService.updateType(type);
    //     this.categoryService.updateCategory(category);
        }
     return "redirect:/types";
     }
    @RequestMapping("/removetype/{id}")
    public String removeType(@PathVariable("id") int id){
    this.typeService.removeType(id);
    return "redirect:/types";
    }
     @RequestMapping("/edittype/{id}")
     public String editType(@PathVariable("id") int id, Model model){
     model.addAttribute("type", typeService.getTypeById(id));
     model.addAttribute("listType", typeService.listType());
    // model.addAttribute("listCategory", categoryService.listCategory());
     return "types";
  }
   @RequestMapping("typedata/{id}")
   public String typeData(@PathVariable("id") int id, Model model){
    model.addAttribute("type", typeService.getTypeById(id));
    // model.addAttribute("category", categoryService.getCategoryById(id));
    return "typedata";
   }
  }

types.jsp

      <body>
      <a href="../../index.jsp">Back to main menu</a>
    <br/>
    <br/>
    <table class="tg">
       <tr>
        <th>
        <c:if test="${!empty type.sort}">Edit existing type</c:if>
        <c:if test="${empty type.sort}">Add new type</c:if>
       </th>
      </tr>
     <tr>
    <td>
        <c:url var="addAction" value="/types/add"/>
        <form:form action="${addAction}" commandName="type">
            <table>
                <c:if test="${!empty type.sort}">
                    <tr>
                        <td><form:label path="id"><spring:message 
         text="ID"/></form:label></td>
                        <td><form:input path="id" readonly="true" size="8" 
     disabled="true"/><form:hidden path="id"/></td>
                    </tr>
                </c:if>
                <tr>
                    <td><form:label path="sort"><spring:message text="Sort"/></form:label></td>
                    <td><form:input path="sort"/></td>
                </tr>
                <tr>
                            <td><form:label path="category"><spring:message 
   text="Category"/></form:label></td>
                       <td>
                           <form:select path="category" cssStyle="width: 
    200px;">
                               <form:option value="-1">Select a 
       category</form:option>
                               <c:forEach items="${listCategory}" 
    var="category">
                                   <form:option value="${category.id}">${category.name_category}</form:option>
                               </c:forEach>
                           </form:select>
                       </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <c:if test="${!empty type.sort}"><input type="submit" value="<spring:message text="Edit Type"/>"></c:if>
                        <c:if test="${empty type.sort}"><input type="submit" value="<spring:message text="Add Type"/>"></c:if>
                    </td>
                </tr>
            </table>
        </form:form>
      </td>
     </tr>
    </table>
   <c:if test="${!empty listType}">
    <table class="tg">
    <tr>
        <th width="60">ID</th>
        <th width="150">Sort</th>
        <th width="150">Category</th>
        <th width="50">Edit</th>
        <th width="50">Delete</th>
    </tr>
    <c:forEach items="${listType}" var="type">
        <tr>
            <td>${type.id}</td>
            <td><a href="/typedata/${type.id}" target="_blank">${type.sort}</a></td>
            <td>${type.category.name_category}</td>
            <td><a href="<c:url value="/edittype/${type.id}"/>">Edit</a></td>
            <td><a href="<c:url value="/removetype/${type.id}"/>">Delete</a></td>
        </tr>
    </c:forEach>
</table>
</c:if>
 </body>

typedata.jsp

<table class="tg">
<tr>
    <th width="60">ID</th>
    <th width="120">Sort</th>
    <th width="120">Category</th>
</tr>
<tr>
    <td>${type.id}</td>
    <td>${type.sort}</td>
    <td>${type.category.name_category}</td>
</tr>
</table>
READ ALSO
Прием платежей в приложении Android

Прием платежей в приложении Android

у меня возник такой вопросДопустим, есть Android приложение , в нем пользователь должен иметь возможность совершать покупки через qiwi, яндекс...

212
Исчезают элементы в cardview

Исчезают элементы в cardview

Элементы cardview выводятся в RecyclerViewПри запуске приложения сначала все нормально

245
Java обработать строку

Java обработать строку

Думаю, будет проще сразу с примера

218
Арифметические действия в sql запросе

Арифметические действия в sql запросе

Нужно обновить в базе информацию, если с момента изменения прошло больше 3-х сутокПоле last_edit содержит время в формате UNIX

193