Hibernate 更新父实体时更新子实体

3
我有两个实体,一个是用户(User),另一个是项目(Projects),它们之间存在@ManyToMany关系,如下所示。
实体类:
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column (name = "id")
    private int id;
    @Column (name = "email")
    private String email;
    @Column (name = "password")
        private String password;
    @Column (name = "last_login")
    private Date lastLogInDate; 
    @ManyToMany(fetch = FetchType.EAGER)
        @Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})
        @JoinTable(name = "project_assigned", joinColumns = { @JoinColumn(name = "fk_user_id")  }, inverseJoinColumns = { @JoinColumn(name = "fk_project_id") } )
    private Set<Projects> projects = new HashSet<Projects>(0);  

    // setter and getter methods.
}

@Entity
@Table(name = "projects")
public class Projects {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @Column (name = "name")
    private String name;    
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "user_projects", joinColumns = { @JoinColumn(name = "fk_project_id") }, inverseJoinColumns = { @JoinColumn(name = "fk_user_id") })
    private Set<User> userSet = new HashSet<User>(0);   

}

DAO类
@Repository
public class UserDAO {

    public User findByCredentials(String email, String password) {
        String queryString = " from User u where u.email = ? and u.password = ?";
        Query query = sessionFactory.getCurrentSession().createQuery(queryString);
        query.setString(0, email);
        query.setString(1, password);       
        return (User) query.uniqueResult();     
    }

    public boolean updateUser(User user) {
        boolean result = true;
        Session session = null;
        try {
            session = sessionFactory.getCurrentSession();
            session.update(user);
        } catch (HibernateException e) {
            result = false;
            logger.error("Can not Update User"+e);
            e.printStackTrace();
        } 
        return result;
    }           
}

服务类。
@Service
@Transactional(readOnly = true,propagation=Propagation.SUPPORTS)
public class UserService {

    @Autowired
    private UserDAO userDAO;

    public User findByCredentials(String userName, String lastName) {
        return userDAO.findByCredentials(userName, lastName);   
    }

    @Transactional(readOnly = false,propagation=Propagation.REQUIRED)
    public boolean updateUser(User user) {
        return userDAO.updateUser(user);
    }
}

其他代码
User user = userService.findByCredentials("xyz@pqr.com", "abc");
user.setLastLogInDate(new Date());
userService.updateUser(user);

我的问题是,当我更新用户的“LastLogInDate”时,所有分配给该用户的项目实体都会被更新(不必要地触发更新语句),这使得我的应用程序性能变得很低。我该如何解决这个问题?以及如何更好地处理它。谢谢您的帮助。
以下是我的 SQL 日志。
DEBUG org.hibernate.SQL#log  - update users set email=?, password=?, last_login=? where id=?
DEBUG org.hibernate.SQL#log  - update user_projects set name=? where id=?
DEBUG org.hibernate.SQL#log  - update user_projects set name=? where id=?
DEBUG org.hibernate.SQL#log  - update user_projects set name=? where id=?
DEBUG org.hibernate.SQL#log  - update user_projects set name=? where id=?
DEBUG org.hibernate.SQL#log  - update user_projects set name=? where id=?

你找到解决方案了吗? - Dmitry Malys
2个回答

2

您必须在级联运行之前设置级联,因为级联无法在运行时(保存)设置:

@Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE})

你至少需要移除CascadeType.MERGE。因为MERGE表示一些复杂的操作,大致相当于“保存”,但更像是“将这个分离的实体推回托管状态并保存其状态更改”。级联意味着所有相关的实体都会以同样的方式被推回,而从.merge()返回的托管实体句柄具有与之关联的所有托管实体。


谢谢您的回复。我已经按照您的建议进行了更改,并将 @Cascade({CascadeType.SAVE_UPDATE,CascadeType.MERGE}) 更改为 **@Cascade({CascadeType.SAVE_UPDATE})**,但它并没有起作用。 - Ashish Jagtap

-1

移除所有级联选项。这将解决您的问题。

1个解决方案:

解决方案1:

用户类:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_projects", joinColumns = { @JoinColumn(name = "fk_project_id") }, inverseJoinColumns = { @JoinColumn(name = "fk_user_id") })
private Set<Projects> projects;

项目类

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_projects", joinColumns = { @JoinColumn(name = "fk_project_id") }, inverseJoinColumns = { @JoinColumn(name = "fk_user_id") })
private Set<User> userSet; 

这应该作为评论发布,而不是作为答案。请删除。 - Thom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接