保存
public void createXXX(XXX xxx) {
Session session = null;
try {
session = getSession();
Transaction tran = session.beginTransaction();
xxx.setCommand(new String(Base64.encode(xxx.getCommand())));
session.save(xxx);
tran.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
更改
public void editXXX(XXX xxx) {
Session session = null;
try {
session = getSession();
Transaction tran = session.beginTransaction();
xxx.setCommand(new String(Base64.encode(xxx.getCommand())));
session.saveOrUpdate(xxx);
tran.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
删除
public void deleteXXX(Integer jobId) {
Session session = null;
try {
session = getSession();
String sql = "delete from xxx where jobid = '"+jobId+"'";
System.out.println(sql);
session.createSQLQuery(sql).executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
Criteria查询
/**
* Criteria无查询条件查询所有
*/
public static void main(String[] args) {
//声明一个集合用来接收结果
List<Login> result=null;
//声明Session
Session session=null;
//初始化以上对象
try{
session = getSession();
//声明Criteria对象传入一个持久化类对象类型
Criteria criteria=session.createCriteria(Login.class);
//查询使用list方法
result=criteria.list();
}catch(HibernateException e){
e.printStackTrace();
}finally{
session.close();
}
//输出结果
for (Login login : result) {
System.out.println("用户名:"+login.getUsername()+" 密码:"+login.getPassword()+" 年龄:"+login.getAge());
}
}