首先要创建实体类 Student.java
package star.july.a_session;
public class Student {
private int id;
private String name;
private String gender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gender=" + gender
+ "]";
}
}
package star.july.a_session;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import star.july.util.HibernateUtil;
public class Demo {
//增加
@Test
public void test(){
Session session = HibernateUtil.getSession();
Transaction ts = session.getTransaction();
try{
//开启事务
ts.begin();
Student s = new Student();
// s.setId(1);
s.setName("杨光");
s.setGender("男");
session.save(s);
ts.commit();
}catch(Exception e){
e.printStackTrace();
ts.rollback();
}
}
//修改
@Test
public void test2(){
Session session = HibernateUtil.getSession();
Transaction ts = session.getTransaction();
try{
//开启事务
ts.begin();
/*Student s = new Student();
s.setId(1);
s.setName("小红");
s.setGender("女");*/
//方式一:
// session.update(s);
//方式二:
/**
* 参数
* class:要查询的实体类的class
* Serializable:要查询的对象的主键号
*/
//先查询
Student stu = (Student)session.get(Student.class, 2);
//再修改
stu.setGender("女");
//不需要调用update方法
System.out.println(stu); //输出:Student [id=2, name=小年, gender=女]
ts.commit();
}catch(Exception e){
e.printStackTrace();
ts.rollback();
}
}
//删除
@Test
public void test3(){
Session session = HibernateUtil.getSession();
Transaction ts = session.getTransaction();
try{
//开启事务
ts.begin();
//方式一
/* Student s = new Student();
s.setId(2);
session.delete(s);*/
//方式二
//先查询再删除
Student stu = (Student)session.get(Student.class, 3);
if(stu!= null ){
session.delete(stu);
}
//提交事务
ts.commit();
}catch(Exception e){
e.printStackTrace();
ts.rollback();
}
}
//查询
@Test
public void test4(){
Session session = HibernateUtil.getSession();
Transaction ts = session.getTransaction();
try{
//开启事务
ts.begin();
//查询一个
//参数一:查询的类型
//参数二:查询的id
// Student stu = (Student)session.get(Student.class, 3);
// System.out.println(stu);
//查询多个
List list = session.createQuery("from Student").list();
for(Student s : list){
System.out.println(s);
}
//提交事务
ts.commit();
}catch(Exception e){
e.printStackTrace();
ts.rollback();
}
}
}