Vue + Spring Jpa创建新实体而不是更新

时间:2018-01-26 12:40:08

标签: hibernate spring-boot vue.js vuejs2 spring-data-jpa

简单地说,我想通过Vue.js更新我的组织实体,但它创建了一个新实体,而不是更新现有记录。

主要问题是添加隐藏的ID字段。我可以通过th:field来处理百里香,但我不能对Vue.js做同样的事。

这是我的观点部分:

<template>
  <div id="app">
    <h2>Organizations</h2>
    <hr>
    <ul>
      <li v-for="organization in organizations">
        ID: {{organization.organizationId}}
        <br>
        Organization Name: {{organization.name}}
        <br>
        Organization Domain: {{organization.domain}}
        <br>

        <div>
          <form @submit.prevent="onUpdt(organization.organizationId)">
            <input type="hidden" v-model="organization.organizationId"/>

            <label for="nameUpd">Name:</label>
            <input v-model="put.name" type="text" id="nameUpd">
            <br>
            <label for="domainUpd">Domain:</label>
            <input v-model="put.domain" type="text" id="domainUpd">
            <br>
            <input type="submit">
          </form>
        </div>
        <br>

      </li>

    </ul>
    <h3>Add new Organiztion</h3>
    <form @submit.prevent="onSubmit">
      <label for="name">Name:</label>
      <input v-model="post.name" type="text" id="name">
      <br>
      <label for="domain">Domain:</label>
      <input v-model="post.domain" type="text" id="domain">
      <br>
      <input type="submit">
    </form>
  </div>
</template>

<script>
  import axios from 'axios';

  const getConfig = {
    method: 'GET',
    url: 'http://localhost:8082/organizations',
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'json'
  };
  const putConfig = {
    method: 'PUT',
    url: 'http://localhost:8082/organizations',
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'json',
    data: this.put
  };

  export default {
    name: 'Demo',

    data() {
      return {
        organizations: [],
        post: {
          name: '',
          domain: ''
        },
        put: {
          name: '',
          domain: ''
        }
      }
    },
    created() {
      axios.request(getConfig)
        .then(response => {
          this.organizations = response.data
        })
        .catch(e => {
          console.log("Error on fetching data with axios. Error: " + e)
        })
    },
    methods: {
      onSubmit() {
        axios.post('http://localhost:8082/organizations', this.post)
          .then(org => {
            this.organizations.push(org.data);
          });
      },
      onUpdt(id) {
        axios.put("http://localhost:8082/organizations/" + id, this.put);
    }
  }
</script>

我的组织实体:

@Entity
@Table(name = "organization")
@EntityListeners(AuditingEntityListener.class)
@Transactional
public class Organization {

    @Id
    @GeneratedValue
    private Long organizationId;

    @NotNull
    @Column(nullable = false)
    private String name;

    @NotNull
    @Column(nullable = false)
    private String domain;

    @CreatedDate
    private LocalDate createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;


    public Organization() {
    }

  //Getters, setters, builerders etc.


}

我的控制器部分用于更新:

@PutMapping(path = "/{id}")
    public ResponseEntity<Organization> updateOrganization(
            @PathVariable(value = "id") Long id, @Valid @RequestBody Organization newOrg) {
        Optional<Organization> organization = organizationRepository.findById(id);
        if (organization.isPresent()) {
            Organization updatedOrg =
                    organizationRepository.save(
                            organization
                                    .get()
                                    .toBuilder()
                                    .name(newOrg.getName())
                                    .domain(newOrg.getDomain())
                                    .build());
            return ResponseEntity.ok(updatedOrg);
        }

        return ResponseEntity.notFound().build();
    }

编辑:

组织存储库:

@Repository
public interface OrganizationRepository extends CrudRepository<Organization, Long> {
  Optional<Organization> findOrganizationByName(String name);
}

非常重要的提醒:邮差表现相同!所以问题不在于vue.js问题。

0 个答案:

没有答案