视频讲解使用的Hibernate3.4,自己做测试使用的是Hibernate5.5.1.-Final版本,通过测试可用。
1、项目目录结构
2、将JPA必要的jar包拷贝的工程的classpath路径下,红色部分,另外还需要数据库驱动包
3、在src目录下新建META-INF目录,并新建persistence.xml文件,配置好数据库和方言等
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<!-- 实体bean的集合,name可以自定义,这里采用的本地事务 -->
<persistence-unit name="sunft_first" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- 当表不存在时,才会创建表 -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<!-- 配置数据库信息 -->
<property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="root" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=UTF-8" />
<!-- 配置Hibernate抓取深度 -->
<property name="hibernate.max_fetch_depth" value="3" />
</properties>
</persistence-unit>
</persistence>
4、新建实体类Person.java
package cn.sunft.bean;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
private Integer id;
private String name;
public Person() {
super();
}
public Person(String name) {
super();
this.name = name;
}
//也可以直接标注在属性上
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5、编写测试类进行测试
package junit.test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.Before;
import org.junit.Test;
import cn.sunft.bean.Person;
/**
* 对Person类进行单元测试
*/
public class PersonTest {
@Before
public void setUpBeforeClass() {
}
@Test
public void save() {
//创建工厂的时候就会创建表,参数值与persistence.xml中的必须一致
EntityManagerFactory entityManagerFactory
= Persistence.createEntityManagerFactory("sunft_first");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();//开启事务
entityManager.persist(new Person("卡卡罗特"));
entityManager.getTransaction().commit();//提交事务
entityManager.close();
entityManagerFactory.close();
}
}
6、数据库中的结果