原文: https://howtodoinjava.com/hibernate/hibernate-insert-query-tutorial/

Hibernate 是 Java 语言的对象关系映射(ORM)库,它提供了将面向对象的域模型映射到传统关系数据库的框架。 这意味着不需要构建和执行与数据库交互的 SQL 查询。 您只需要通过调用 Hiberate API 来指示 Hiberate,Hiberate 将代表您创建并执行这些 SQL 查询。

在这个 Hiberate 教程中,我给出了在单个表中插入数据的示例。 我们在应用中有一个对象,即Employee。 我们想将其存储在数据库中。 Employee类具有以下属性:

  • 员工编号 – 整数
  • 电子邮件 – 字符串
  • 名 – 字符串
  • 姓 – 字符串

它可以有更多的字段,但是我仅用四个来举例说明。

1. Hiberate 实体类

Hiberate 与标记为 Hiberate 实体的 Java POJO 类进行对话。 要将 Java 类转换为实体,我们需要在其上应用@Entity注解。 还有其他 Hiberate 注解,例如@Table@Column@Id等,它们有助于将实体字段映射到数据库表和列 。

应用注解后,Employee实体类如下所示。

  1. @Entity
  2. @Table(name = "EMPLOYEE", uniqueConstraints = {
  3. @UniqueConstraint(columnNames = "ID"),
  4. @UniqueConstraint(columnNames = "EMAIL") })
  5. public class EmployeeEntity implements Serializable
  6. {
  7. private static final long serialVersionUID = -1798070786993154676L;
  8. @Id
  9. @GeneratedValue(strategy = GenerationType.IDENTITY)
  10. @Column(name = "ID", unique = true, nullable = false)
  11. private Integer id;
  12. @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
  13. private String email;
  14. @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
  15. private String firstName;
  16. @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
  17. private String lastName;
  18. //Getters and setters
  19. }

2. Hiberate 配置

下一步是在“hibernate.cgf.xml”文件中配置 Hiberate。 该文件包含系统和数据库连接元数据中的所有可用实体。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  8. <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property>
  9. <property name="hibernate.connection.password">password</property>
  10. <property name="hibernate.connection.username">root</property>
  11. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  12. <property name="show_sql">true</property>
  13. <property name="hbm2ddl.auto">create</property>
  14. <mapping class="hibernate.test.dto.EmployeeEntity"></mapping>
  15. </session-factory>
  16. </hibernate-configuration>

3. Hibernate SessionFactory

现在,Hiberate 配置已经就绪,我们必须构建 Hiberate 会话工厂。 会话工厂用于获取数据库以及各种活动(如提交和回滚)的连接。

  1. public class HibernateUtil
  2. {
  3. private static final SessionFactory sessionFactory = buildSessionFactory();
  4. private static SessionFactory buildSessionFactory()
  5. {
  6. try
  7. {
  8. // Create the SessionFactory from hibernate.cfg.xml
  9. return new AnnotationConfiguration().configure(new File("hibernate.cgf.xml")).buildSessionFactory();
  10. }
  11. catch (Throwable ex) {
  12. // Make sure you log the exception, as it might be swallowed
  13. System.err.println("Initial SessionFactory creation failed." + ex);
  14. throw new ExceptionInInitializerError(ex);
  15. }
  16. }
  17. public static SessionFactory getSessionFactory() {
  18. return sessionFactory;
  19. }
  20. public static void shutdown() {
  21. // Close caches and connection pools
  22. getSessionFactory().close();
  23. }
  24. }

4. Hibernate 插入查询示例

最后,我们将使用此 Hiberate 会话工厂执行插入查询以将员工保存在数据库中。

  1. public class TestHibernateInsert {
  2. public static void main(String[] args)
  3. {
  4. Session session = HibernateUtil.getSessionFactory().openSession();
  5. session.beginTransaction();
  6. //Add new Employee object
  7. EmployeeEntity emp = new EmployeeEntity();
  8. emp.setEmail("lokesh@mail.com");
  9. emp.setFirstName("lokesh");
  10. emp.setLastName("gupta");
  11. //Save the employee in database
  12. session.save(emp);
  13. //Commit the transaction
  14. session.getTransaction().commit();
  15. HibernateUtil.shutdown();
  16. }
  17. }

程序日志。

  1. Hibernate: insert into EMPLOYEE (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)

让我们验证数据库中的数据。

Hibernate 插入查询教程 - 图1

Hibernate 插入查询示例

5. 故障排除

  1. 请确保在项目中添加 Hiberate 和 mysql 驱动依赖项。 在 Maven 中,这些如下:
    1. <dependency>
    2. <groupId>org.hibernate</groupId>
    3. <artifactId>hibernate-commons-annotations</artifactId>
    4. <version>3.0.0.ga</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.hibernate</groupId>
    8. <artifactId>hibernate-annotations</artifactId>
    9. <version>3.3.0.ga</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>mysql</groupId>
    13. <artifactId>mysql-connector-java</artifactId>
    14. <version>5.1.6</version>
    15. </dependency>
  1. 验证hibernate.cgf.xml文件存在并且具有有效的数据库元数据。

下载源码

学习愉快!