我有两个实体:
1)
@Entity
@Table(name = "users")
public class User {
private String username;
private String password;
private String name;
private String surname;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "depId")
private Department department;
private boolean enabled;
private Set<UserRole> userRole = new HashSet<UserRole>(0);
private Set<Equipment> equipment = new HashSet<Equipment>();
2)
@Entity
@Table(name = "department")
public class Department {
private int depId;
private String name;
private String adress;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "department")
private Set<User> user = new HashSet<User>();
如何编写HQL查询,将值INSERT到User。不是从其他表。我有JSP表单,其中插入表单。我想从thats表单中添加值。 我有'删除'方法的问题。
在UserDAOImpl:
@Override
public User findByUserName(String username) {
return (User) getSession().get(User.class, username);
}
@Override
public void delete(String username) {
getSession().delete(findByUserName(username));
}
当我使用此方法时,它会删除Department中的“department”和UserRole表中的“user_role”。但我想只删除用户。
更新
此问题已修复。但我有第二个问题。我有第二个实体,如Depatment,名为UserRole。并且有相同的方法。我需要方法:
UserRoleDAOImpl:
@Override
public Set<UserRole> findByRole (Set<UserRole> userRole){
}
DepartmentDAOImpl:
@Override
public Department findByDepartmentName(String departmentName) {
List<Department> departments = getSession()
.createQuery("select d from Department d where d.name =:departmentName")
.setParameter("departmentName", departmentName).list();
return departments.size() == 0 ? null : departments.get(0);
}
控制器:
@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
private ModelAndView updateUser(@ModelAttribute("users") User user, BindingResult result) {
ModelAndView model = new ModelAndView();
department = departmentService.findByDepartmentName(user.getDepartment().getName());
user.setDepartment(department);
userRole = userRoleService.findByRole(user.getUserRole());
user.setUserRole(userRole);
userService.update(user);
model.addObject("allUsers", userService.getAllUsers());
model.setViewName("superAdmin");
return model;
}
我不知道怎么写userRoleService.findByRole(user.getUserRole())
。它不能正常工作。
答案 0 :(得分:0)
由于您正在使用注释,因此需要阅读有关插入db的hibernate事务。希望您已经在db中创建了一个表。
您可以为应用程序创建SessionFactory对象,并使用Criteria api将表单值保存到db。 请查找示例链接
http://www.dineshonjava.com/2013/08/spring-crud-example-using-many-to-one.html#.V8aQp_l97IU
如果您仍然只想编写查询,则可以使用带有hql的条件
https://www.mkyong.com/hibernate/hibernate-criteria-examples/
由于 普拉迪普