我是春季新人。我有一个名为SampleStore的项目。在我的项目中创建的一些实体,例如User,UserRole,Product,Orders,CartItem和....,但是我有问题。当我尝试添加新的用户应用程序时,它不会出现错误,并且在databse中插入了新记录。但是当我尝试插入新订单时,我会收到错误消息。
User.java
@Entity
@Table(name = "users")
public class User implements Serializable, UserDetails {
private static final long serialVersionUID = -8245107356306518473L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "username", nullable = false, unique = true, length = 50)
private String username;
@Column(name = "password", nullable = false, length = 60)
private String password;
@Column(name = "enabled", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean enabled;
@Column(name = "expired", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonExpired;
@Column(name = "locked", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean accountNonLocked;
@Column(name = "credential", nullable = true, columnDefinition = "tinyint(1) default 1")
private boolean credentialsNonExpired;
@Column(name = "gender", nullable = true)
private char gender;
@Column(name = "address", nullable = true)
private String address;
@Column(name = "phonenumber", nullable = true)
private String phoneNumber;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Comment> comments = new ArrayList<Comment>();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private List<Orders> orders = new ArrayList<Orders>();
public User() {
}
public User(String username, String password, boolean enabled) {
this.username = username;
this.password = password;
this.enabled = enabled;
}
public User(String username, String password, boolean enabled, Set<UserRole> userRoles) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.userRoles = userRoles;
}
public User(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked, Set<UserRole> authorities) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.userRoles = authorities;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", enabled=" + enabled
+ ", gender=" + gender + ", address=" + address + ", phoneNumber=" + phoneNumber + ", userRoles="
+ userRoles + "]";
}
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
}
UserRole.java
@Entity
@Table(name = "user_roles", uniqueConstraints = @UniqueConstraint(columnNames = { "username", "role" }))
public class UserRole {
private Integer userRoleId;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_role_id", unique = true, nullable = false)
public Integer getUserRoleId() {
return this.userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name = "role", nullable = false, length = 45)
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
}
}
Orders.java
@Entity
@Table(name = "orders")
public class Orders implements Serializable {
private static final long serialVersionUID = -3672662224925418969L;
@Id
@Column(name = "ord_id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@DateTimeFormat(pattern = "yyyy-mm-dd")
@Column(name = "orderDate", nullable = false)
private Date orderDate;
@DateTimeFormat(pattern = "yyyy-mm-dd")
@Column(name = "delivery", nullable = false)
private Date deliveryDate;
@Column(name = "success", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean success;
@Column(name = "cancel", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean canceled;
@Column(name = "cause", nullable = true)
private String cancelCause;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "order")
private List<CartItem> items = new ArrayList<CartItem>();
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name="username",nullable=false)
private User user;
public Orders() {
}
public Orders(Date deliveryDate, List<CartItem> items, User user) {
this.orderDate = new Date();
this.deliveryDate = deliveryDate;
this.items = items;
this.user = user;
}
public Orders(List<CartItem> items, User user) {
this.orderDate = new Date();
this.items = items;
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Date getDeliveryDate() {
return deliveryDate;
}
public void setDeliveryDate(Date deliveryDate) {
this.deliveryDate = deliveryDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public boolean isCanceled() {
return canceled;
}
public void setCanceled(boolean canceled) {
this.canceled = canceled;
}
public String getCancelCause() {
return cancelCause;
}
public void setCancelCause(String cancelCause) {
this.cancelCause = cancelCause;
}
public List<CartItem> getItems() {
return items;
}
public void setItems(List<CartItem> items) {
this.items = items;
}
}
CartItem.java
@Entity
@Table(name = "saleitems", uniqueConstraints = {})
public class CartItem implements Serializable {
private static final long serialVersionUID = 7968604053015663078L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private Long id;
@Column(name = "prd_id", nullable = false)
private Product product;
@Column(name = "quantity", nullable = false, columnDefinition = "int(11) default 1")
private Integer quantity;
@Column(name = "totalprice", nullable = false)
private BigDecimal totalprice;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "orderid", nullable = false)
private Orders order;
public CartItem(Product product, Integer quantity) {
this.product = product;
this.quantity = quantity;
setTotalprice();
}
public CartItem() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getTotalprice() {
return totalprice;
}
public void setTotalprice() {
this.totalprice = getProduct().getPrice().multiply(new BigDecimal(getQuantity()));
}
public Orders getOrder() {
return order;
}
public void setOrder(Orders order) {
this.order = order;
}
}
这是我的控制器代码的一部分,该用户用于保存新用户和保存新订单。
@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public ModelAndView saveNewUser(@ModelAttribute User user) {
ModelAndView model = new ModelAndView();
user.setEnabled(true);
user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
UserRole role = new UserRole(user, "ROLE_USER");
Set<UserRole> roles = new HashSet<UserRole>();
roles.add(role);
user.setUserRoles(roles);
String result = userService.addUser(user);
if (!result.toLowerCase().startsWith("error")) {
model.setViewName("loginForm");
} else {
model.setViewName("newuser");
model.addObject("error", result);
}
return model;
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/store/addorder", method = RequestMethod.GET)
public ModelAndView addOrder(HttpSession session) {
ModelAndView model = new ModelAndView();
// create list of products that we have to add in orders
System.err.println("item get to retrieving---------------");
List<CartItem> items = (List<CartItem>) session.getAttribute("cart");
for (CartItem cartItem : items) {
System.err.println(cartItem.getProduct());
}
// find user by username to set orders userinfo
System.err.println("user information get to retriving---------------");
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userService.findByUsername(username);
System.err.println(user);
// new order generated and setter methods invoke
System.err.println("new order generated-------------------");
Orders order = new Orders(items, user);
Date d = new Date();
Date delivery = StoreUtils.deliveryDate(d, 3);
order.setOrderDate(d);
order.setDeliveryDate(delivery);
order.setUser(user);
order.setItems(items);
String addOrders = orderService.addOrders(order);
System.err.println("new order add status " + addOrders + "-------------");
System.err.println(order);
// change product quantity after adding new order
for (int i = 0; i < items.size(); i++) {
Integer qSale = items.get(i).getQuantity() * (-1);
productService.rechargeProduct(items.get(i).getProduct(), qSale);
}
if (!addOrders.toLowerCase().contains("error")) {
model.setViewName("successorder");
model.addObject("order", order);
model.addObject("message", addOrders);
session.setAttribute("cart", null);
} else {
session.setAttribute("error", addOrders);
model.setViewName("redirect:/addtocartlist");
}
return model;
}
最后,这是我在dao类中保存用户和订单的代码。
UserDaoImpl.java
public String addUser(User user) {
String result = "";
String pass = encoder.encode(user.getPassword());
user.setPassword(pass);
try {
session().save(user);
session().flush();
result = "success";
} catch (Exception e) {
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error :user is already joined to store!";
else
result = "error :" + e.getCause().getMessage();
}
return result;
}
OrderDaoImpl.java
public String addOrders(Orders orders) {
String result = "";
try {
session().save(orders);
result = "success";
} catch (Exception e) {
if (e.getCause() != null)
if (e.getCause().getMessage().toLowerCase().contains("duplicate"))
result = "error this order already was exist";
else
result = "error " + e.getCause().getMessage();
else {
result = "error " + e.getMessage();
}
System.err.println(result);
} finally {
session().clear();
}
return result;
}
所有代码都相似,但是结果不同。当尝试添加新订单时,出现此异常:
非空属性引用一个空值或瞬态值:com.softup.store.entity.CartItem.order
答案 0 :(得分:0)
设置关系的双方。在每个项目上调用setOrder()。在用户setOrder()上也是如此。