配置maven依赖时,hibernate的最新版本
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
与以前版本的实现代码有些区别,好了!让我们来看看hibernate5.4.0.Final对数据库的操作:
前面的实体类和映射文件
新增记录
public class TestInsertStudent {
public static void main(String[] args) {
//读取总的配置文件
Configuration configuration=new Configuration();
configuration.configure("/hibernate.cfg.xml");
//创建session工厂
SessionFactory factory=configuration.buildSessionFactory();
//打开session
Session session=factory.openSession();
//开启事务
Transaction transaction=session.beginTransaction();
//增删改查
Student student=new Student();
student.setXm("zby");
student.setAge(12);
session.save(student);
//提交事务
transaction.commit();
//不使用连接池,就是关闭连接;使用连接池,session.close()只是把连接放回连接池
session.close();
}
}
查询,根据主键查找
public class TsetSelectById {
//hibernate默认开启一级缓存
public static void main(String[] args) {
//读取总的配置文件
Configuration configuration=new Configuration();
configuration.configure("/hibernate.cfg.xml");
//创建session工厂
SessionFactory factory=configuration.buildSessionFactory();
//打开session
Session session=factory.openSession();
//get和load的区别
/*
//查询为null 返回null
Student student=session.get(Student.class, 1);
if (student==null) {
System.out.println("查无此人");
}
else {
System.out.println(student.getXm()+"\t"+student.getAge());
}*/
/*
//查询为null 报异常
Student student=session.load(Student.class, -1);
if (student==null) {
System.out.println("查无此人");
}
else {
System.out.println(student.getXm()+"\t"+student.getAge());
}*/
//表名---》类,字段---》属性,不能用select *
String hql="from Student where xh=?0";
//session.createQuery(hql);
Query<Student> query=session.createQuery(hql,Student.class);
//第一个?是0,值是1
query.setParameter(0, 1);
Student student=query.uniqueResult();
if (student==null) {
System.out.println("查无此人");
}
else {
System.out.println(student.getXm()+"\t"+student.getAge());
}
}
}
修改
public class TestUpdateStudent {
public static void main(String[] args) {
//先查找,再修改
// 1.读取总的配置文件
Configuration cfg = new Configuration();
cfg.configure("/hibernate.cfg.xml");
// 2.创建session工厂
SessionFactory factory = cfg.buildSessionFactory();
// 3.打开session
Session session = factory.openSession();
Student stu = session.get(Student.class, 1);
if (stu==null)
{
System.out.println("查无此人");
}
else
{
session.getTransaction().begin();
stu.setXm("子不语");
session.update(stu);
session.getTransaction().commit();
}
}
}