保存ManyToOne

时间:2016-08-19 13:19:27

标签: java spring hibernate jpa crud

我有两个双向关系实体(ManyToOne,OneToMany) 两张桌子House&房间。房子有很多房间 我需要用它的地址和两个(可能是更晚的)房间来保存房子。 以下代码添加了没有房间的房屋和地址(room = null)。

我怎样才能做到这一点?

我对房间的投入是否合适?例如在PHP中我会有 name="roomName[]"

我认为Hibernate将为我做一切:)特别是当我使用cascadeType.ALL

@Entity
@Data
public class House {

  @Id
  @GeneratedValue(strategy = IDENTITY)
  private Long id;

  private String name;

  @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinColumn(name = "address_id")
  private PostalAddress address;

  @OneToMany(cascade = CascadeType.ALL, mappedBy = "house", fetch = FetchType.EAGER)
  private Set<Room> rooms;
}

@Entity
@Data
public class Room {

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

  private String name;

  @NotNull
  private int capacity;

  @NotNull
  @ManyToOne
  @JoinColumn(name = "house_id")
  private House house;
}

创建数据库条目表单

<input type="text" name="name" placeholder="house name..." />
<input type="text" name="address.addressLocality" placeholder="locality" />
<input type="text" name="address.postalCode" placeholder="postalCode" />
<input type="text" name="address.streetAddress" placeholder="street" />
<input type="text" name="room.name" placeholder="room name" />
<input type="text" name="room.capacity" placeholder="capacity" />
<input type="text" name="room.name" placeholder="room name" />
<input type="text" name="room.capacity" placeholder="capacity" />

最后我的控制器和存储库

public interface RoomRepository extends CrudRepository<Room, Long> {
}

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String saveHouse(@ModelAttribute("house/new") House house, BindingResult bindingResult, Model model) {

  houseRepository.save(house);

  return "redirect:/house/list";

}

//重要编辑

我有小费可能是错的,但我无法解决这个问题。我正在使用Thymeleaf。当House有许多房间(设置房间)时,包含房间输入的表单部分不正确。默认情况下,我在表格中显示4行(房间名称,容量)

<tr th:each="i,iterStat : ${#numbers.sequence( 1, 4)}">
   <td class="col-xs-9 col-md-9"><input type="text" name="rooms.name" th:value="ROOM + ' ' + ${iterStat.current}"  class="form-control"/> </td>
   <td class="col-xs-2 col-md-2"><input type="number" name="rooms.capacity" min="1" step="1" value="4" class="form-control"/> </td>
   <td class="col-xs-1 col-md-1"><button type="button" class="btn red pull-right" onclick="removeTableRow(this)"> <i class="fa fa-trash"></i> </button></td>
</tr>

当用户想要添加更多或更少的房间时,他(使用jQuery)删除/添加带输入的表格行 我试图将输入名称更改为

  

个:字段= “* {。房间[ $ {iterStat.current} ]名称}”

但不是这样。那么如何填充这些字段?

1 个答案:

答案 0 :(得分:0)

试用House实体映射:

@OneToOne(fetch = FetchType.EAGER, mappedBy = "house", cascade = {CascadeType.ALL})
private PostalAddress address;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "house", cascade = {CascadeType.ALL}, orphanRemoval = true)
private Set<Room> rooms;

的PostalAddress:

@OneToOne
@JoinColumn(name="house")
private House house;

间:

@NotNull
@ManyToOne
@JoinColumn(name="house")
private House house;