Hibernate一对多不工作

时间:2015-01-19 15:00:15

标签: java hibernate spring-mvc one-to-many

我有两个关于一对多映射的问题。

代码:

User.java

public class User {

private String firstName;

@Id
@SequenceGenerator(name = "userID", sequenceName = "userID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "userID")
@Column(name = "id")
private Long id;

private String lastName;

@Column(name = "reset", nullable = false)
private Integer passwordReset;

@Column(name = "useremail", nullable = false, unique = true)
@Email
@NotEmpty
private String email;
@Column(name = "password", nullable = false)
private String password;

@OneToOne(mappedBy = "user", optional = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private Role role;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private List<CreditCards> creditCards;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private List<WashingOrder> orderList;

@Column(unique = true)
@NotEmpty(message = "{username}")
private String username;

public String getFirstName() {
    return firstName;
}

public Long getId() {
    return id;
}

public String getLastName() {
    return lastName;
}

public String getEmail() {
    return email;
}

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

public String getPassword() {
    return password;
}

public Role getRole() {
    return role;
}

public String getUsername() {
    return username;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

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

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public void setPassword(String password) {
    this.password = password;
}

public void setRole(Role role) {
    this.role = role;
}

public void setUsername(String username) {
    this.username = username;
}

public List<CreditCards> getCreditCards() {
    return creditCards;
}

public void setCreditCards(List<CreditCards> creditCards) {
    this.creditCards = creditCards;
}

public Integer getPasswordReset() {
    return passwordReset;
}

public void setPasswordReset(Integer passwordReset) {
    this.passwordReset = passwordReset;
}

public List<WashingOrder> getOrderList() {
    return orderList;
}

public void setOrderList(List<WashingOrder> orderList) {
    this.orderList = orderList;
}

@Override
public String toString() {
    return "User [id=" + id + ", firstName=" + firstName + ", lastName="
            + lastName + ", username=" + username + ", password="
            + password + ", role=" + role + "]";
}

}

WashingOrder.java

    public class WashingOrder {

@Id
@SequenceGenerator(name = "orderNo", sequenceName = "orderNo")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "orderNo")
@Column(name = "orderNo")
private Long orderNo;

@Column(name = "totalClothes", nullable = false)
@NotNull
private Integer totalClothes;

@Column(name = "mensCloth", nullable = true)
private Integer mensCloth;

@Column(name = "womensCloth", nullable = true)
private Integer womensCloth;

@Column(name = "otherCloth", nullable = true)
private Integer otherClothes;

@Column(name = "deliveryDate", nullable = true)
@DateTimeFormat(pattern = "yyyy-mm-dd")
private Date deliveryDate;

@Column(name = "status", nullable = true)
private String orderStatus;

public Long getOrderNo() {
    return orderNo;
}

public void setOrderNo(Long orderNo) {
    this.orderNo = orderNo;
}

public Integer getTotalClothes() {
    return totalClothes;
}

public void setTotalClothes(Integer totalClothes) {
    this.totalClothes = totalClothes;
}

public Integer getMensCloth() {
    return mensCloth;
}

public void setMensCloth(Integer mensCloth) {
    this.mensCloth = mensCloth;
}

public Integer getWomensCloth() {
    return womensCloth;
}

public void setWomensCloth(Integer womensCloth) {
    this.womensCloth = womensCloth;
}

public Integer getOtherClothes() {
    return otherClothes;
}

public void setOtherClothes(Integer otherClothes) {
    this.otherClothes = otherClothes;
}

public Date getDeliveryDate() {
    return deliveryDate;
}

public void setDeliveryDate(Date deliveryDate) {
    this.deliveryDate = deliveryDate;
}

public String getOrderStatus() {
    return orderStatus;
}

public void setOrderStatus(String orderStatus) {
    this.orderStatus = orderStatus;
}

@Override
public String toString() {
    return "WashingOrder [orderNo=" + orderNo + ", totalClothes="
            + totalClothes + ", mensCloth=" + mensCloth + ", womensCloth="
            + womensCloth + ", Others=" + otherClothes + ", deliveryDate="
            + deliveryDate + ", orderStatus=" + orderStatus + "]";
}

}

此处用户试图通过调用以下方法来下订单。

   public Long placeOrder(WashingOrder order) {
    Session session = sessionFactory.getCurrentSession();
    long id = 1;
    Query query = session.createQuery("from user where id =" + id);
    User emp6 = (User) session.load(User.class, new Long(1));
    User user = (User) query.uniqueResult();
    List<WashingOrder> washingOrder = new ArrayList<WashingOrder>();
    washingOrder.add(order);
    System.out.println("washingOrder" + washingOrder);
    emp6.setOrderList(washingOrder);
    session.persist(order);
    session.persist(user);

    Long orderID = (long) 1;
    return orderID;
 }

问题:

  1. 现在我的硬编码用户ID为1.如果用户登录后如何动态传递。 我是否在会话中保留用户名或ID,并在每种方法中传递它以获取用户详细信息。

  2. 当我尝试将订单添加到特定用户时,现有用户值ID将从现有数据中删除并更新为新数据。当我尝试将订单添加到用户时,请查看hibernate查询输出。

  3. 输出:

      Hibernate: insert into ClothDetails (deliveryDate, mensCloth, status, otherCloth, totalClothes, womensCloth) values (?, ?, ?, ?, ?, ?)
      Hibernate: select creditcard0_.id as id6_2_0_, creditcard0_.creditID as creditID1_3_0_, creditcard0_.creditID as creditID1_3_1_, creditcard0_.creditcard_number as creditca2_3_1_, creditcard0_.expiry_month as expiry_m3_3_1_, creditcard0_.expiry_year as expiry_y4_3_1_, creditcard0_.payment_type as payment_5_3_1_ from usercreditcards creditcard0_ where creditcard0_.id=?
      Hibernate: update ClothDetails set id=null where id=?
      Hibernate: update ClothDetails set id=? where orderNo=?
    

2 个答案:

答案 0 :(得分:0)

是的,您需要在会话中存储用户ID,并在需要值的任何地方使用它。如果更改了用户标识,则需要更新存储在会话中的值。基本上,您需要在会话中使用用户ID,并且需要确保它是新鲜的。

答案 1 :(得分:0)

  1. servlet规范中有一个Principal类,用于管理登录用户。如果您不在servlet环境中(您没有告诉),那么您应该保留对User对象的引用。这使您可以访问用户和用户ID。不要在断开连接的号码上进行中继。

  2. 您的关系映射不匹配。 User.java中的@JoinColumn(name =“id”)指向“id”。这是你的外键吗?你确定不是“orderNo”吗?

  3. 你也应该确保WashingOrder和User之间也有关系,因为现在没有明确的参考映射。