Hibernate?状态
package Test;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import Hibernate.entity.Admin;
import Hibernate.entity.Role;
import Hibernate.entity.Student;
public class Practice {
public static void main(String[] args) {
Session session = new Configuration().configure().buildSessionFactory().openSession();
try {
session.beginTransaction();
Student Student=new Student();
Student.setName("学生");
Student.setSex("女");
Student.setVersion(5);
session.save(Student);
session.update(Student);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
hibernate有三种状态:
transient(瞬时状态)
persistent(持久化状态)
detached(离线状态)
区分:
session.beginTransaction();之后
new Student();是transient(瞬时状态)
----------
在session.beginTransaction();
和session.getTransaction().commit();
之间都可以理解为persistent(持久化状态)
----------
然后就是游离状态
引用图片地址:http://www.cnblogs.com/xiaoluo501395377/p/3380270.html
引用图片地址:http://blog.csdn.net/fg2006/article/details/6436517
参考;
Hibernate?删除(基本功能)
Student Student=new Student();
Student.setId(1280);
session.delete(Student);
/*该表和关系表必须有无参数构造函数*/
Hibernate?添加(基本功能)
session.save(entity);
Hibernate?修改(基本功能)
session.update(entity);
Hibernate?查找(基本功能)
--load
Student Student = session.load(Student.class, 1279);
System.out.println(Student.getName());
--get
Student Student = session.get(Student.class, 1279);
System.out.println(Student.getName());
--使用load方法
Student Student = session.load(Student.class, 1279);
System.out.println(Student.getId());
控制台不会输出查询语句
--使用get方法
Student Student = session.load(Student.class, 1279);
System.out.println(Student.getId());
控制台直接输出查询语句
--区别
get方法会在调用之后立即向数据库发出sql语句(不考虑缓存的情况下),返回持久化对象;
load方法会在调用后返回一个代理对象,该代理对象只保存了实体对象的id,直到使用对象的非主键属性时才会发出sql语句。
Hibernate?查找(高级查询)
//查找Student类所有数据返回一个集合
Collection<Student> Studentlist = session.createQuery("select t from Student t").list();
for (Student object : Studentlist) {
System.out.println(object.getName());
}