最近接手的项目使用Hibernate框架操作MySQL数据库,就想记录一下基本操作,以下是查询、修改数据的例子:
public class HibernateData {
private static final Logger logger = LoggerFactory.getLogger(HibernateData.class);
/**
* 根据电话号查询用户ID
* @param telephone
* @return
*/
public String getData(String telephone) {
try {
String hql = "from UserVO WHERE telephone=:telephone ";//UserVO是实体类名,和数据库中的表对应
Configuration config = new Configuration().configure();//读取默认的hibernate.cfg.xml的文件
SessionFactory factory = config.buildSessionFactory(); //创建SessionFactory
Session session = factory.openSession(); //创建Session
Query query = session.createQuery(hql);
query.setString("telephone", telephone);
UserVO userVO=(UserVO)query.uniqueResult();//确定返回的数据为一条或0条,就使用uniqueResult(),否则用query.list().get(0);query.list()得到的是返回数据的集合
if (userVO!=null) {
return userVO.getId();
}
session.close();//关闭会话
}catch (Exception e){
logger.error("查询用户ID失败");
e.printStackTrace();
}
return "";
}
/**
* 根据电话号修改上级ID
* @param userVO
* @param telephone
*/
public void updateData(UserVO userVO,String telephone) {
try {
String hql = "UPDATE UserVO SET superior=:superior WHERE telephone=:telephone ";
Configuration config = new Configuration().configure();
SessionFactory factory = config.buildSessionFactory(); //创建SessionFactory
Session session = factory.openSession(); //创建Session
session.beginTransaction();//开启事务
Query query = session.createQuery(hql);
query.setParameter("superior", userVO);
query.setParameter("telephone", telephone);
query.executeUpdate();//执行修改
session.getTransaction().commit();//提交
session.close();//关闭会话
}catch (Exception e){
logger.error("修改上级id失败");
e.printStackTrace();
}
}