我尝试使用spring和hibernate构建app,buat我有很多关系表的问题。我成功添加到数据库,但我有一个问题,收集数据。 有这种关系的用户和角色表。 我尝试获取所有用户角色数据,例如,如果用户有2个角色(Role_user和Role_admin),我想从特定用户那里收集所有角色。但是把脚本,我的日志hibernate成功收集数据,但之后hibernate也删除了用户角色数据。这很奇怪,我试图找到这个bug,因为我没有把删除方法。
这里是我的scipt
user.java
@Entity
@Table
public class User {
@Id
@GeneratedValue
private int id;
private String userName;
private String email;
private String password;
private boolean enabled;
@ManyToMany
@JoinTable
private List<Role> roles;
/**
@OneToOne
private Employee employee;
**/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Role.java
@Entity
@Table
public class Role {
@Id
@GeneratedValue
private int id;
private String name;
@ManyToMany(mappedBy="roles")
private List<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
UserController.java
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value="user", method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("user", new User());
model.addAttribute("userlist", this.userService.findAll());
return "user";
}
//for add and edit
@RequestMapping(value= "/addAndEditUser", method = RequestMethod.POST)
public String addAndEditUser(@ModelAttribute("user") User user){
if(user.getId() == 0){
//new employee status, call save
this.userService.save(user);
}else{
this.userService.update(user);
}
return "redirect:/user";
}
//For add
@RequestMapping(value= "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user){
//new employee status, call save
this.userService.save(user);
return "redirect:/user";
}
//for edit
@RequestMapping(value= "/updateUser", method = RequestMethod.POST)
public String updateUser(@ModelAttribute("user") User user){
//existing Employee status, call update function from service
userService.update(user);
return "redirect:/user";
}
@RequestMapping("/removeUser/{id}")
public String removeUser(@PathVariable("id") int id){
this.userService.delete(id);
return "redirect:/user";
}
//for call edit in list
@RequestMapping("/editUser/{id}")
public String editUser(@PathVariable("id") int id, Model model){
model.addAttribute("religionlist", this.userService.findAll());
model.addAttribute("user", this.userService.findById(id));
return "formUser";
}
@RequestMapping("/users/{id}")
public String detail(Model model, @PathVariable int id){
model.addAttribute("users", userService.findOneWithRole(id));
return "user-detail";
}
}
userSericeImpl.java
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Transactional
public User findById(int id) {
return userDao.findById(id);
}
@Transactional
public List<User> findAll() {
return userDao.findAll();
}
@Transactional
public void save(User user) {
user.setEnabled(true);
userDao.save(user);
}
@Transactional
public void update(User user) {
userDao.update(user);
}
@Transactional
public void delete(int id) {
userDao.delete(id);
}
@Transactional
public User findOne(int id) {
return userDao.findOne(id);
}
@Transactional
public User findOneWithRole(int id) {
return userDao.findOneWithRole(id);
}
}
UserDaoImpl.java
@Repository
public class UserDaoImpl implements UserDao{
private static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;
@Autowired
private RoleDao roleDao;
public User findById(int id) {
return (User)sessionFactory.getCurrentSession().get(User.class, id);
}
@SuppressWarnings("unchecked")
public List<User> findAll() {
Session session = this.sessionFactory.getCurrentSession();
List<User> userList = session.createQuery("from User").list();
return userList;
}
public void save(User user) {
Session session = this.sessionFactory.getCurrentSession();
List<Role> roles = new ArrayList<Role>();
//roles.add(roleDao.findById(2));
roles.add(roleDao.findByName("ROLE_USER"));
user.setRoles(roles);
session.persist(user);
}
public void update(User user) {
Session session = this.sessionFactory.getCurrentSession();
session.update(user);
logger.info("Employee Status updated successfully, departement Details="+user);
}
public void delete(int id) {
sessionFactory.getCurrentSession().delete(findById(id));
}
public User findOne(int id) {
return (User)sessionFactory.getCurrentSession().get(User.class, id);
}
public User findOneWithRole(int id) {
User user = findById(id);
List<Role> roles = roleDao.findByUser(id);
user.setRoles(roles);
return user;
}
}
RoleDaoImpl.java
@Repository
public class RoleDaoImpl implements RoleDao{
private static final Logger logger = LoggerFactory.getLogger(RoleDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;
public Role findById(int id) {
return (Role)sessionFactory.getCurrentSession().get(Role.class, id);
}
@SuppressWarnings("unchecked")
public List<Role> findAll() {
Session session = this.sessionFactory.getCurrentSession();
List<Role> roleList = session.createQuery("from Role").list();
return roleList;
}
public void save(Role role) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(role);
}
public void update(Role role) {
Session session = this.sessionFactory.getCurrentSession();
session.update(role);
logger.info("Employee Status updated successfully, departement Details="+role);
}
public void delete(int id) {
sessionFactory.getCurrentSession().delete(findById(id));
}
public Role findByName(String name) {
Query query = sessionFactory.getCurrentSession().createQuery("from Role where name=:name");
query.setParameter("name", name);
Role role = (Role)query.uniqueResult();
return role;
}
@SuppressWarnings("unchecked")
public List<Role> findByUser(int id) {
Session session = this.sessionFactory.getCurrentSession();
List<Role> roles = session.createQuery("from Role where id=:id").setString("id", "%" + id + "%").list();
return roles;
}
}
用户detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<h1>${users.userName}</h1>
<br>
User Role
<c:forEach items="${users.roles}" var="role">
<h1>${role.name}</h1>
</c:forEach>
当我看到用户详细信息时记录应用程序:
10:34:32,801 DEBUG AnnotationTransactionAttributeSource:108 - Adding transactional method 'UserServiceImpl.findOneWithRole' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
Hibernate:
select
user0_.id as id6_0_,
user0_.email as email6_0_,
user0_.enabled as enabled6_0_,
user0_.password as password6_0_,
user0_.userName as userName6_0_
from
User user0_
where
user0_.id=?
Hibernate:
select
role0_.id as id5_,
role0_.name as name5_
from
Role role0_
where
role0_.id=?
Hibernate:
delete
from
User_Role
where
users_id=?
如何调用delete方法? 我怎么能解决这个问题? 我想列出特定用户的所有角色。
提前感谢:) 如果你不介意教我如何更新和删除(多对多)......:)
答案 0 :(得分:0)
在你的控制器中,我看到你调用userService.findOneWithRole(id)来获取用户的详细信息,如下所示:
@RequestMapping("/users/{id}")
public String detail(Model model, @PathVariable int id){
model.addAttribute("users", userService.findOneWithRole(id));
return "user-detail";
}
回溯到UserDaoImpl类中的findOneWithRole(int id)方法,您将看到您为用户分配了不必要的角色,并且还会导致DELETE发生。您可以尝试删除它,看看它是否有效。
public User findOneWithRole(int id) {
User user = findById(id);
List<Role> roles = roleDao.findByUser(id);
user.setRoles(roles); // <-- THIS LINE
return user;
}