Hibernate基础操作
首先建立一个实体类Dept.java,并建立映射文件,使Hibernate能正常工作。
import java.util.Date;
import java.util.Objects;
public class Dept {
private int deptno;
private String dname;
private String address;
private String tel;
private Date credate;
//Setter,Getter略
//toString略
}
- 新增操作
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
import java.util.Date;
public class TestInsert {
public static void main(String[] args) {
boolean flag = HibernateSessionFactory.getSession().save(getDept())!=null;
HibernateSessionFactory.getSession().beginTransaction().commit();
HibernateSessionFactory.closeSession();
System.out.println(flag);
}
public static Dept getDept(){
Dept dept = new Dept();
dept.setDeptno(2);
dept.setDname("财务部");
dept.setAddress("**市**县");
dept.setCredate(new Date());
dept.setTel("123456789");
return dept;
}
}
执行结果:
2. 修改操作
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
import java.util.Date;
public class TestUpdate {
public static void main(String[] args) {
HibernateSessionFactory.getSession().update(getDept());
HibernateSessionFactory.getSession().beginTransaction().commit();
HibernateSessionFactory.closeSession();
}
public static Dept getDept(){
Dept dept = new Dept();
dept.setDeptno(2);
dept.setDname("财务部");
dept.setAddress("**县");
dept.setCredate(new Date());
dept.setTel("987654321");
return dept;
}
}
执行结果:
3. 删除操作
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
public class TestDelete {
public static void main(String[] args) {
Dept dept = new Dept();
dept.setDeptno(1);
HibernateSessionFactory.getSession().delete(dept);
HibernateSessionFactory.getSession().beginTransaction().commit();
HibernateSessionFactory.closeSession();
}
}
执行结果:
此时发现所有的方法设计上都存在问题,update()和delete()方法没有返回值,无法知道是更新成功了还是失败了。所有的更新操作都要进行事务处理,否则无法真正发出。
- 查询操作(Session查询)
Session接口里面本身所定义的数据查询只有根据ID查询的操作方法,但是这个方法却有两个定义。
根据主键查询:public Object get(Class clazz,Serializable id);
根据主键查询:public Object get(Class theClass,Serializable id);
get()方法
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
public class TestGet {
public static void main(String[] args) {
Dept dept = (Dept) HibernateSessionFactory.getSession().get(Dept.class,3);
System.out.println(dept);
HibernateSessionFactory.closeSession();
}
}
查询结果
load()方法
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
public class TestLoad {
public static void main(String[] args) {
Dept dept = (Dept) HibernateSessionFactory.getSession().load(Dept.class,3);
System.out.println(dept);
HibernateSessionFactory.closeSession();
}
}
此时发现当指定的索引不存在时,使用get方法依然会发出查询指令,查询结果返回null,但使用load方法则会抛出异常。