JPA:就是由Sun公司提供的一套对于持久层操作的标准(接口加文档),没有具体的实现。
Hibernate:是Gavin King 开发的一套对于持久层操作的自动ORM框架。
Hibernate JPA:是在Hibernate3.2版本中,提供的对于JPA标准的实现。提供了一套按照JPA标准来实现持久层开发的APi。
下面具体的代码实现:
1.导入Maven依赖:
<dependencies>
<!--Spring Ioc相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.3.18</version>
</dependency>
<!--Spring Aop的相关依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.8.RC2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.18</version>
</dependency>
<!--Spring jdbc的相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.18</version>
</dependency>
<!--spring orm的相关依赖-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.18</version>
</dependency>
<!--单元测试用的依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
</dependency>
<!--日志依赖-->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!--Hibernate的核心依赖,9个必须要导入-->
<!-- https://mvnrepository.com/artifact/antlr/antlr -->
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.dom4j/dom4j -->
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.geronimo.specs/geronimo-jta_1.1_spec -->
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jta_1.1_spec</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.common/hibernate-commons-annotations -->
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>5.1.2.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss/jandex -->
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.logging/jboss-logging -->
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.4.1.Final</version>
</dependency>
<!--mysql数据驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<!--连接池相关的依赖-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.6.7.Final</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>mchange-commons-java</artifactId>
<version>0.2.19</version>
</dependency>
<!--hibernate jpa 相关依赖-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.6.7.Final</version>
</dependency>
</dependencies>
创建applicationContext.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置读取properties文件的工具类-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置c3p0数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--Spring整合 Hibernate JPA ,配置EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--hibernate相关属性的注入:-->
<!--database配置数据库类型-->
<property name="database" value="MYSQL"/>
<!--开启正向工程,自动创建表-->
<property name="generateDdl" value="true"/>
<!--开启显示执行的sql-->
<property name="showSql" value="true"/>
</bean>
</property>
<!--配置要扫描的实体的包-->
<property name="packagesToScan">
<list>
<value>com.haiexijun.pojo</value>
</list>
</property>
</bean>
<!--配置Hibernate的事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--开启注解事务处理-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--配置springIOC的注解扫描-->
<context:component-scan base-package="com.haiexijun"/>
</beans>
创建数据库hibernate02
jdbc配置文件:
jdbc.url=jdbc:mysql://localhost:3306/hibernate02
jdbc.driver.class=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=zc20020106
2.编写实体类
package com.haiexijun.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "t_users")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增
@Column(name = "userid")
private Integer userId;
@Column(name = "username")
private String userName;
@Column(name = "userage")
private Integer userAge;
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 getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAge=" + userAge +
'}';
}
}
3.创建usersDao类及其实现类
package com.haiexijun.dao.impl;
import com.haiexijun.dao.usersDao;
import com.haiexijun.pojo.Users;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
@Repository
public class usersDaoImpl implements usersDao {
@PersistenceContext(name = "entityManagerFactory")
private EntityManager entityManager;
@Override
public void insertUsers(Users users) {
entityManager.persist(users);
}
@Override
public void updateUsers(Users users) {
entityManager.merge(users);
}
@Override
public void deleteUsers(Users users) {
Users u =selectUsersById(users.getUserId());
this.entityManager.remove(u);
}
@Override
public Users selectUsersById(Integer userid) {
return entityManager.find(Users.class,userid);
}
@Override
public List<Users> selectUserByAge(Integer age) {
//这里from会报错,但是没有毛病!
return entityManager.createQuery("from Users where userAge = :abc").setParameter("abc",age).getResultList();
}
@Override
public List<Users> selectUserByAgeUseSQL(Integer age) {
//这里要绝对注意哦,在Hibernate JPA中如果通过?还传入参数,查数是从1开始的。我们之前学习的Hibernate是从0开始的。
return entityManager.createNativeQuery("select * from t_users where userage=?",Users.class).setParameter(1,age).getResultList();
}
@Override
public List<Users> selectUserByAgeUseQBC(Integer age) {
//CriteriaBuilder对象:创建一个CriteriaQuery,创建查询条件
CriteriaBuilder builder=entityManager.getCriteriaBuilder();
//CriteriaQuery对象:执行查询的Criteria对象
CriteriaQuery<Users> query=builder.createQuery(Users.class);
//获取要查询的实体类对象
Root<Users> root=query.from(Users.class);
//封装查询条件
Predicate predicate=builder.equal(root.get("userAge"),age);
query.where(predicate);
//执行查询
TypedQuery<Users> typedQuery=entityManager.createQuery(query);
List<Users> users=typedQuery.getResultList();
return users;
}
}
测试代码:
package com.haiexijun.dao.impl;
import com.haiexijun.pojo.Users;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class usersDaoImplTest extends TestCase {
@Autowired
private usersDaoImpl usersDao;
@Test
@Transactional
@Rollback(value = false)
public void testInsertUsers() {
Users users=new Users();
users.setUserName("张五");
users.setUserAge(20);
usersDao.insertUsers(users);
}
@Test
@Transactional
@Rollback(value = false)
public void testUpdateUsers() {
Users users=new Users();
users.setUserId(1);
users.setUserName("张四");
users.setUserAge(20);
usersDao.updateUsers(users);
}
@Test
@Transactional
@Rollback(value = false)
public void testDeleteUsers() {
Users users=new Users();
users.setUserId(1);
users.setUserName("张四");
users.setUserAge(20);
usersDao.deleteUsers(users);
}
@Test
@Transactional
@Rollback(value = false)
public void testSelectUsersById() {
Users users= usersDao.selectUsersById(1);
System.out.println(users);
}
@Test
@Transactional
@Rollback(value = false)
public void testSelectUserByAge() {
List<Users> usersList = usersDao.selectUserByAge(20);
System.out.println(usersList);
}
@Test
@Transactional
@Rollback(value = false)
public void testSelectUserByAgeUseSQL() {
System.out.println(usersDao.selectUserByAgeUseSQL(20));
}
@Test
@Transactional
@Rollback(value = false)
public void testSelectUserByAgeUseQBC() {
System.out.println(usersDao.selectUserByAgeUseQBC(20));
}
}