Hibernate 简易入门教程

Hibernate 是一款开源的 ORM 框架,它可以将 Java 对象映射到关系型数据库中的表。Hibernate 的设计思想是尽量让开发人员从 SQL 中解脱出来,从而提高开发效率和程序的可维护性。本篇文章将介绍 Hibernate 的一些基本概念和使用方法,并通过一个简单的案例进行说明。

一、Hibernate 的基本概念

1. SessionFactory

SessionFactory 是 Hibernate 的核心接口之一,它用于创建 Session 对象,Hibernate 应用中只需要一个 SessionFactory,一般会把 SessionFactory 声明为全局变量,以便于其他类的调用。

2. Session

Session 是 Hibernate 操作数据库的基本单位,每个 Session 对象代表了与数据库的一次会话。Session 对象可以根据应用程序的需要进行创建、关闭和删除等操作。

3. Transaction

Transaction 用于管理事务,事务是指一组数据库操作,这些操作要么全都成功,要么都失败。在 Hibernate 中,事务是基于 Session 的,所以需要在 Session 上开启事务,当事务完成后,Hibernate 会自动提交或回滚。

4. Hibernate 配置文件

Hibernate 的配置文件是 Hibernate 应用的重要组成部分,它通常是一个 XML 文件,包含了几乎所有的 Hibernate 配置信息,例如数据库连接 URL、用户名、密码、是否缓存 SQL 语句等等。

5. 映射文件

映射文件是 Hibernate 使用的另一种重要配置文件,它描述了 Java 对象和数据库表之间的映射关系。映射文件包括了表名、列名、主键、外键、关联关系等信息。

6. Hibernate 映射类型

Hibernate 映射类型是指 Java 类型和数据库类型之间的映射关系,Hibernate 内置了很多映射类型,例如字符串、数字、日期、枚举等等。

二、Hibernate 的使用方法

1. 添加 Hibernate 的依赖

在 Maven 中使用 Hibernate,需要在 pom.xml 文件中添加以下依赖:

```

org.hibernate

hibernate-core

5.4.0.Final

```

2. 编写 Hibernate 配置文件

在 src/main/resources 目录下创建名为 hibernate.cfg.xml 的文件,内容如下所示:

```

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

org.hibernate.dialect.MySQL5Dialect

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/test?useSSL=false

root

123456

create-drop

```

其中,hibernate.connection.* 属性用于指定数据库连接信息,hibernate.hbm2ddl.auto 属性用于指定 Hibernate 自动创建表结构的方式。

3. 编写映射文件

在 src/main/resources 目录下创建名为 User.hbm.xml 的文件,内容如下所示:

```

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

```

其中,name 属性用于指定实体类的名称,table 属性用于指定数据库表的名称,id 元素表示主键,generator 元素用于指定主键生成策略,property 元素用于指定普通列。

4. 编写实体类

创建名为 User 的实体类,代码如下所示:

```

public class User {

private int id;

private String name;

private int age;

private String email;

// 省略 getter 和 setter 方法

}

```

5. 编写测试代码

在 src/test/java 目录下创建名为 Test 的测试类,代码如下所示:

```

public class Test {

private SessionFactory sessionFactory;

@Before

public void init() {

Configuration config = new Configuration().configure();

sessionFactory = config.buildSessionFactory();

}

@After

public void destroy() {

sessionFactory.close();

}

@org.junit.Test

public void testSave() {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

User user = new User();

user.setName("John");

user.setAge(20);

user.setEmail("john@example.com");

session.save(user);

tx.commit();

session.close();

}

}

```

其中,init() 方法用于创建 SessionFactory 对象,destroy() 方法用于关闭 SessionFactory 对象,testSave() 方法用于测试插入一条记录。

6. 运行测试

在 IntelliJ IDEA 中,右键点击 Test 类中的 testSave() 方法,选择 Run Test,即可启动测试。如果一切正常,Hibernate 将会自动创建表结构并插入数据,测试成功后,我们可以在数据库中查看到插入的数据。

三、案例说明

这里我们举例说明如何使用 Hibernate 完成一个简单的学生信息管理系统。系统包括两个实体类:Student 和 Course,其中 Student 实体类包括学生的基本信息,Course 实体类包括课程的基本信息。Student 和 Course 之间是多对多的关系,即一个学生可以选修多门课程,一门课程也可以有多个学生选修。

1. 编写 Hibernate 配置文件

同上述方法,编写 Hibernate 配置文件 hibernate.cfg.xml。

2. 编写映射文件

(1) Student.hbm.xml,用于将 Student 实体类映射到数据库表 student:

```

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

```

注意,这里在 Student 映射文件中使用了 set 元素,用于创建多对多关系。set 元素包含了两个子元素:key 元素用于指定关联列,many-to-many 元素用于指定关联实体类。

(2) Course.hbm.xml,用于将 Course 实体类映射到数据库表 course:

```

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

```

这里,Course 映射文件中的 set 元素和 Student 映射文件中的 set 元素是类似的,在 key 元素和 many-to-many 元素中分别指定了关联列和关联实体类。

3. 编写实体类

(1) Student.java,代码如下所示:

```

public class Student {

private int id;

private String name;

private int age;

private int gender;

private Set courses;

// 省略 getter 和 setter 方法

}

```

注意,在 Student 实体类中声明了一个名为 courses 的 Set 变量,用于存储选课记录。

(2) Course.java,代码如下所示:

```

public class Course {

private int id;

private String name;

private Set students;

// 省略 getter 和 setter 方法

}

```

注意,在 Course 实体类中声明了一个名为 students 的 Set 变量,用于存储选课记录。

4. 编写测试代码

(1) StudentDao.java,用于对 Student 实体类进行增删查改操作:

```

public class StudentDao {

private SessionFactory sessionFactory;

public StudentDao() {

Configuration config = new Configuration().configure();

sessionFactory = config.buildSessionFactory();

}

public boolean addStudent(Student student) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.save(student);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public boolean deleteStudent(Student student) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.delete(student);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public boolean updateStudent(Student student) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.update(student);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public Student getStudent(int id) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

Student student = session.get(Student.class, id);

tx.commit();

return student;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return null;

} finally {

session.close();

}

}

}

```

(2) CourseDao.java,用于对 Course 实体类进行增删查改操作:

```

public class CourseDao {

private SessionFactory sessionFactory;

public CourseDao() {

Configuration config = new Configuration().configure();

sessionFactory = config.buildSessionFactory();

}

public boolean addCourse(Course course) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.save(course);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public boolean deleteCourse(Course course) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.delete(course);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public boolean updateCourse(Course course) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

session.update(course);

tx.commit();

return true;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return false;

} finally {

session.close();

}

}

public Course getCourse(int id) {

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

try {

Course course = session.get(Course.class, id);

tx.commit();

return course;

} catch (Exception e) {

if (tx != null) {

tx.rollback();

}

e.printStackTrace();

return null;

} finally {

session.close();

}

}

}

```

(3) Test.java,用于测试 StudentDao 和 CourseDao 中的方法:

```

public class Test {

private static StudentDao studentDao = new StudentDao();

private static CourseDao courseDao = new CourseDao();

@org.junit.Test

public void testAddStudent() {

Student student = new Student();

student.setName("Zhang San");

student.setAge(19);

student.setGender(1);

boolean result = studentDao.addStudent(student);

Assert.assertTrue(result);

}

@org.junit.Test

public void testDeleteStudent() {

Student student = studentDao.getStudent(1);

boolean result = studentDao.deleteStudent(student);

Assert.assertTrue(result);

}

@org.junit.Test

public void testUpdateStudent() {

Student student = studentDao.getStudent(1);

student.setName("Li Si");

boolean result = studentDao.updateStudent(student);

Assert.assertTrue(result);

}

@org.junit.Test

public void testGetStudent() {

Student student = studentDao.getStudent(1);

Assert.assertNotNull(student);

}

@org.junit.Test

public void testAddCourse() {

Course course = new Course();

course.setName("English");

boolean result = courseDao.addCourse(course);

Assert.assertTrue(result);

}

@org.junit.Test

public void testDeleteCourse() {

Course course = courseDao.getCourse(1);

boolean result = courseDao.deleteCourse(course);

Assert.assertTrue(result);

}

@org.junit.Test

public void testUpdateCourse() {

Course course = courseDao.getCourse(1);

course.setName("Math");

boolean result = courseDao.updateCourse(course);

Assert.assertTrue(result);

}

@org.junit.Test

public void testGetCourse() {

Course course = courseDao.getCourse(1);

Assert.assertNotNull(course);

}

@org.junit.Test

public void testAddStudentToCourse() {

Student student = studentDao.getStudent(1);

Course course = courseDao.getCourse(1);

student.getCourses().add(course);

course.getStudents().add(student);

boolean result1 = studentDao.updateStudent(student);

boolean result2 = courseDao.updateCourse(course);

Assert.assertTrue(result1 && result2);

}

@org.junit.Test

public void testRemoveStudentFromCourse() {

Student student = studentDao.getStudent(1);

Course course = courseDao.getCourse(1);

student.getCourses().remove(course);

course.getStudents().remove(student);

boolean result1 = studentDao.updateStudent(student);

boolean result2 = courseDao.updateCourse(course);

Assert.assertTrue(result1 && result2);

}

}

```

这里的测试代码中,分别测试了对 Student 和 Course 实体类的增删查改操作,以及多对多关系的添加和删除操作。

结语

本文介绍了 Hibernate 的基本概念和使用方法,并通过一个简单的学生信息管理系统进行了示例说明。Hibernate 是一款非常优秀的 ORM 框架,可以大大简化数据库操作,提高开发效率,同时也提高了程序的可维护性和可扩展性。建议开发人员在进行 Java Web 开发时将 Hibernate 纳入考虑。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.37seo.cn/

点赞(52) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部