我有一个HQL查询
private static final String USER_ID_PARAM = "u_id";
private static final String DELETE_BY_USER_ID =
"delete from Data where user_id=:" + USER_ID_PARAM;
删除方法
@Override
public void deleteUserData(long userId) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session s = sf.openSession();
try {
Query q = s.createQuery(DELETE_BY_USER_ID);
q.setParameter(USER_ID_PARAM, userId);
q.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (s != null && s.isOpen()) {
s.close();
}
}
}
但这不起作用。似乎executeUpdate()永远执行。
有趣的是SELECT查询效果很好
private static final String SELECT_BY_USER_ID =
"from Data where user_id=:" + USER_ID_PARAM;
@Override
public List<Data> userData(long userId) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session s = sf.openSession();
try {
Query q = s.createQuery(SELECT_BY_USER_ID);
q.setParameter(USER_ID_PARAM, userId);
q.setCacheable(true);
@SuppressWarnings("unchecked")
List<Data> userData = (List<Data>) q.list();
return userData;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (s != null && s.isOpen()) {
s.close();
}
}
}
创建“数据”表格查询
CREATE TABLE数据(id SERIAL,url VARCHAR(128),登录VARCHAR(64), password VARCHAR(128),电子邮件VARCHAR(128),额外VARCHAR(256),user_id BIGINT UNSIGNED,PRIMARY KEY(id),FOREIGN KEY(user_id)REFERENCES 用户(id)ON DELETE RESTRICT ON UPDATE CASCADE);
@Override
public boolean deleteUserData(long userId) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session s = sf.getCurrentSession();
Transaction tran = s.beginTransaction();
try {
Query q = s.createQuery(DELETE_BY_USER_ID);
q.setParameter(USER_ID_PARAM, userId);
int updated = q.executeUpdate();
tran.commit();
return updated > 0;
} catch (Exception e) {
e.printStackTrace();
if (tran != null) {
tran.rollback();
}
return false;
}
}