如果项目出现超过10次,请将其删除并存储新项目

时间:2016-06-22 06:06:51

标签: mysql database hibernate

我想为用户存储10个以前的密码,以便他/她不使用旧密码。为此,我创建了一个包含3列的表:

  • id
  • password
  • userId

现在,如果第11次忘记密码并更新密码,则应删除其第一个旧密码,从而存储新密码。什么是sql查询?

我首先检查了count useridentity哪个效果很好:

SELECT userIdentity, COUNT(userIdentity) FROM passwordhistory;

现在,如果count >10,我想删除与之关联的最小ID的行。

DELETE FROM passwordhistory 
 WHERE id = (SELECT MIN(id) 
               FROM passwordhistory where userIdentity in
                       (SELECT userIdentity, COUNT(userIdentity) 
                          FROM passwordhistory
                       )
            )

但是,如果使用userIdentity删除count>10,则不完整。

PasswordHistory.java

package com.tcs.webrtc.model;

 import java.io.Serializable; 
 @Entity
 @Table(name="passwordhistory")
 public class PasswordHistory implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 2621325802545502360L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;

public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
@NotNull    
private String userIdentity;
@NotNull
private String password;
public String getUserIdentity() {
    return userIdentity;
}
public void setUserIdentity(String userIdentity) {
    this.userIdentity = userIdentity;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
}

1 个答案:

答案 0 :(得分:0)

由于你使用mysql,你应该创建一个要删除的id列表,然后删除它们:

创建列表:

Session session=sessionFactory.getCurrentSession(); 
String queryToCheckPassword="
SELECT MIN(id) 
       FROM passwordhistory where userIdentity in
               (SELECT userIdentity 
                  FROM passwordhistory 
                 group by userIdentity 
                having COUNT(userIdentity) >10
               )
"; 
List listToDel = session.createSQLQuery(queryToCheckPassword).list();
return listToDel .size()>0?true:false;

通过id删除(这是java男人来的地方);

<for each item in listToDel >
     delete from passwordhistory where id = :id