- 创建工程,并导入相对应的jar包。
![图1.png](http://upload-images.jianshu.io/upload_images/3110861-942130069a5d4436.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
图1.png
- 创建实体类, 此处使用的注解必须是javax.persistence包下的,否则会报异常。
package com.mazaiting.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Student")
public class Student {
private Long id;
private String name;
private String age;
public Student() {
}
@Id
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
- 在根目录创建配置文件
<?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://127.0.0.1:3306/test</property>
<!-- 数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否输出sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 是否格式化sql语句 -->
<property name="hibernate.format_sql">true</property>
<!-- 生成具体的表结构 -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- 引入映射文件 -->
<mapping class="com.mazaiting.entity.Student"/>
</session-factory>
</hibernate-configuration>
- 测试
package com.mazaiting.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mazaiting.entity.Student;
public class StudentTest {
/**
* 会话工厂
*/
private SessionFactory sessionFactory;
/**
* 会话对象
*/
private Session session;
/**
* 事务对象
*/
private Transaction transaction;
/**
* 初始化
*/
@Before
public void setUp(){
// 创建配置
Configuration config = new Configuration().configure("hibernate.cfg.xml");
// 创建会话工厂
sessionFactory = config.buildSessionFactory();
// 创建会话对象
session = sessionFactory.openSession();
// 开启事务
transaction = session.beginTransaction();
}
/**
* 释放资源
*/
@After
public void tearDown(){
// 提交事务
transaction.commit();
// 关闭会话
session.close();
// 关闭会话工厂
sessionFactory.close();
}
/**
* 测试方法
*/
@Test
public void testSaveStudent(){
// 生成学生对象
Student student = new Student();
student.setId(1L);
student.setName("mazaiting");
student.setAge("23");
session.save(student);
}
}