//新增]
@Test
public void add(){
config = new Configuration();
sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
session = sessionfactory.openSession();
ts = session.beginTransaction();
User user = new User();
user.setName("QQ");
user.setPwd("123");
session.save(user);
ts.commit();
session.close();
}
//HQL 查询-----------------------------
@Test
public void sel(){
config = new Configuration();
sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
session = sessionfactory.openSession();
ts = session.beginTransaction();
Query query = session.createQuery("from User user where user.name=? and user.pwd=?");
query.setString(0, "www");
query.setString(1, "888");
List uu = (List) query.list();
for(int i =0;i<uu.size();i++){
User user = (User) uu.get(i);
System.out.println(user.getName() +"-------"+ user.getPwd());
}
session.close();
}
//HQL 删除
@Test
public void del(){
config = new Configuration();
sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
session = sessionfactory.openSession();
ts = session.beginTransaction();
String hql="delete from User user where user.id=?";
Query queryupdate=session.createQuery(hql);
queryupdate.setInteger(0, 5);
int ret=queryupdate.executeUpdate();
if(ret >0 ){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
ts.commit();
}
//HQL 修改 -----------------------------------------
@Test
public void update(){
config = new Configuration();
sessionfactory = config.configure("hibernate.cfg.xml").buildSessionFactory();
session = sessionfactory.openSession();
ts = session.beginTransaction();
String hql = "update User user set user.name=?,user.pwd=? where user.id=?";
Query queryupdate=session.createQuery(hql);
queryupdate.setString(0, "ABCDE");
queryupdate.setString(1, "AAA");
queryupdate.setInteger(2,6);
int ret=queryupdate.executeUpdate();
if(ret >0 ){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
ts.commit();
}