一)JPA简介
JPA是一套标准规范的API,而Hibernate是一个ORM自动持久化框架
JPA方法:
1、entityManager.find(Class<T> entityClass, Object primaryKey);
根据主键查找数据;如果主键格式不正确,会抛出illegalArgumentException异常;如果主键在数据库未找到数据返回null;
2、entityManager.persist(Object entity);
新增数据;如果entity的主键不为空,而数据库没有该主键,会抛出异常;如果entity的主键不为空,而数据库有该主键,且entity的其他字段与数据库不同,persist后不会更新数据库;
3、entityManager.merge(T entity);
将 Detached状态的Entity实例转至Managed状态;
4、entityManager.remove(Object entity);
删除数据;只能将Managed状态的Entity实例删除,由此Entity实例状态变为Removed;
5、entityManager.clear();
将所有的Entity实例状态转至Detached状态;
6、entityManager.flush();
将所有Managed状态的Entity实例同步到数据库;
7、entityManager.refresh(Object entity);
加载Entity实例后,数据库该条数据被修改,refresh该实例,能得到数据库最新的修改,覆盖原来的Entity实例;
二)创建一个Maven项目
项目结构图如下:
在pom.xml文件中引入Hibernate的jar
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oyj.jpa</groupId>
<artifactId>oyj_hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- hibernate jar -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<!-- oracle jdbc jar-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.6.0</version>
</dependency>
</dependencies>
</project>
三)创建JPA的配置文件persistence.xml
注意:在创建Maven项目时,在项目src/main/resources/下可能没有META-INF文件夹,需要自己手动创建META-INF文件夹。
<?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">
<persistence-unit name="myhibernate_jpa" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- 必须配置 -->
<!-- mysql
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/xm"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value="admin"/>
-->
<!-- oracle -->
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
<property name="hibernate.connection.username" value="oysept"/>
<property name="hibernate.connection.password" value="oysept"/>
<!-- 可选配置 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<!-- DDL语句生成策略
update的含义:当程序运行会自动检测实体类和数据库的表结构是否有差异,一旦有会立即更新表结构
使用场景:
适合:开发阶段
不适合:线上阶段
<property name="hibernate.hbm2ddl.auto" value="update"/>
-->
</properties>
</persistence-unit>
</persistence>
四)创建实体类
先在oracle中创建一个类,作为一个测试类,脚本如下:
create table employee (
userid number primary key,
username varchar2(100),
sex number
);
select count(0) from employee;
drop table employee;
delete from employee;
commit;
select * from employee;
用注解的方式创建一个Employee实体类
package com.oyj.jpa.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "employee")
public class EmployeeEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="userid")
private Integer userID;
@Column(name="username")
private String userName;
@Column(name="sex")
private Integer sex;
public Integer getUserID() {return userID;}
public void setUserID(Integer userID) {this.userID = userID;}
public String getUserName() {return userName;}
public void setUserName(String userName) {this.userName = userName;}
public Integer getSex() {return sex;}
public void setSex(Integer sex) {this.sex = sex;}
@Override
public String toString() {
return "EmployeeEntity{userid: " + this.userID + ", userName: "
+ this.userName + ", sex: " + this.sex + " }";
}
}
五)新增Employee数据
package com.oyj.jpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.oyj.jpa.entity.EmployeeEntity;
public class SessionAddEmployee {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
EntityTransaction txn = null;
try {
// myhibernate_jpa是配置在persistence.xml中
entityManagerFactory = Persistence.createEntityManagerFactory("myhibernate_jpa");
entityManager = entityManagerFactory.createEntityManager();
txn = entityManager.getTransaction();
txn.begin();
Long beginTime = System.currentTimeMillis(); // 开始时间
EmployeeEntity entity = null;
EmployeeEntity en = null;
for (int i = 0; i < 10000; i++) { // 循环批量插入数据, 一条一条插入
int userid = (i+1);
// 实体类
entity = new EmployeeEntity();
entity.setUserID(userid);
entity.setUserName("userName" + userid);
entity.setSex(1);
// 当表里存在主键约束时, 需要判断数据是否已存在, 否则会报错
en = entityManager.find(EmployeeEntity.class, userid);
if (en != null) {
entityManager.merge(entity); // 修改
} else {
entityManager.persist(entity); // 新增
}
}
txn.commit();
Long endTime = System.currentTimeMillis(); // 结束时间
System.out.println("单条数据插入or修改, 执行总耗时: " + (endTime - beginTime) + "毫秒");
} catch (RuntimeException e) {
if ( txn != null && txn.isActive()) txn.rollback();
throw e;
} finally {
if (entityManager != null) {
entityManager.close();
}
}
}
}
新增数据效果图:
六)查询Employee数据
package com.oyj.jpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import com.oyj.jpa.entity.EmployeeEntity;
public class QueryEmployee {
public static void main(String[] args) {
// myhibernate_jpa是配置在persistence.xml中
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myhibernate_jpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
// 根据ID查询单条数据
EmployeeEntity c = em.find(EmployeeEntity.class, 1);
System.out.println("查询Employee结果: \n" + c);
tx.commit();
em.close();
}
}
查询效果图打印:
识别二维码关注个人微信公众号
本章完结,待续,欢迎转载!
本文说明:该文章属于原创,如需转载,请标明文章转载来源!