原文: 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实体类如下所示。
@Entity@Table(name = "EMPLOYEE", uniqueConstraints = {@UniqueConstraint(columnNames = "ID"),@UniqueConstraint(columnNames = "EMAIL") })public class EmployeeEntity implements Serializable{private static final long serialVersionUID = -1798070786993154676L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "ID", unique = true, nullable = false)private Integer id;@Column(name = "EMAIL", unique = true, nullable = false, length = 100)private String email;@Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)private String firstName;@Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)private String lastName;//Getters and setters}
2. Hiberate 配置
下一步是在“hibernate.cgf.xml”文件中配置 Hiberate。 该文件包含系统和数据库连接元数据中的所有可用实体。
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedemo</property><property name="hibernate.connection.password">password</property><property name="hibernate.connection.username">root</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><property name="hbm2ddl.auto">create</property><mapping class="hibernate.test.dto.EmployeeEntity"></mapping></session-factory></hibernate-configuration>
3. Hibernate SessionFactory
现在,Hiberate 配置已经就绪,我们必须构建 Hiberate 会话工厂。 会话工厂用于获取数据库以及各种活动(如提交和回滚)的连接。
public class HibernateUtil{private static final SessionFactory sessionFactory = buildSessionFactory();private static SessionFactory buildSessionFactory(){try{// Create the SessionFactory from hibernate.cfg.xmlreturn new AnnotationConfiguration().configure(new File("hibernate.cgf.xml")).buildSessionFactory();}catch (Throwable ex) {// Make sure you log the exception, as it might be swallowedSystem.err.println("Initial SessionFactory creation failed." + ex);throw new ExceptionInInitializerError(ex);}}public static SessionFactory getSessionFactory() {return sessionFactory;}public static void shutdown() {// Close caches and connection poolsgetSessionFactory().close();}}
4. Hibernate 插入查询示例
最后,我们将使用此 Hiberate 会话工厂执行插入查询以将员工保存在数据库中。
public class TestHibernateInsert {public static void main(String[] args){Session session = HibernateUtil.getSessionFactory().openSession();session.beginTransaction();//Add new Employee objectEmployeeEntity emp = new EmployeeEntity();emp.setEmail("lokesh@mail.com");emp.setFirstName("lokesh");emp.setLastName("gupta");//Save the employee in databasesession.save(emp);//Commit the transactionsession.getTransaction().commit();HibernateUtil.shutdown();}}
程序日志。
Hibernate: insert into EMPLOYEE (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)
让我们验证数据库中的数据。

Hibernate 插入查询示例
5. 故障排除
- 请确保在项目中添加 Hiberate 和 mysql 驱动依赖项。 在 Maven 中,这些如下:
<dependency><groupId>org.hibernate</groupId><artifactId>hibernate-commons-annotations</artifactId><version>3.0.0.ga</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-annotations</artifactId><version>3.3.0.ga</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency>
- 验证
hibernate.cgf.xml文件存在并且具有有效的数据库元数据。
学习愉快!
