Spring Data JPA基本增删改查和JPQL查询(含完整代码和视频连接)

  • 问题:SpringDataJPA怎么使用?

一、考察目标

  • 主要考核SpringDataJPA的用法

二、题目分析

spring data jpa 的使用步骤(下面有具体实现细节)

  • 1.创建maven工程并导入依赖

  • 2.添加配置

  • 3.实体类添加注解

  • 4.编写dao接口

  • 5.编写测试类

三、应用场景

  • spring data jpa 是针对jpa规范中具体实现的在封装,hibernate框架就是jpa规范的具体实现。

四、总结

主要考察的是:

  • 1.spring data jpa 的环境搭建
  • 2.spring data jpa 的常用注解
  • 3.spring data jpa 的dao编写要求

其中spring data jpa 的使用步骤

首先看一下项目的结构

Spring Data JPA基本增删改查和JPQL查询(含完整代码和视频连接)

点击即可进入视频学习网站

1.导入依赖

  • 在pom.xml文件导入以下依赖
<?xml version="1.0" encoding="UTF-8"?>
<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>cn.itcast</groupId>
<artifactId>jpa-day2</artifactId>
<version>1.0-SNAPSHOT</version> <properties>
<spring.version>5.0.2.RELEASE</spring.version>
<hibernate.version>5.0.7.Final</hibernate.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<c3p0.version>0.9.1.2</c3p0.version>
<mysql.version>5.1.6</mysql.version>
</properties> <dependencies>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency> <!--spring beg -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency> <!-- spring对orm框架的支持包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency> <!-- spring end--> <!-- hibernate beg -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.2.1.Final</version>
</dependency>
<!-- hibernate end--> <!-- c3p0 beg -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.version}</version>
</dependency>
<!-- c3p0 end --> <!-- log end -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end --> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency> <!-- spring data jpa 的坐标 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.9.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency> <!-- el beg 使用 spring data jpa必须引入 -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency> <dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
<!-- el end -->
</dependencies>
</project>

2.配置

  • 在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:lang="http://www.springframework.org/schema/lang"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- spring 和 spring data jpa 的配置--> <!-- 1.创建entityManagerFactory对象交给spring容器管理-->
<bean id ="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 配置的扫描的包(实体类所在的包)-->
<property name="packagesToScan" value="cn.itcast.domain"/>
<!-- jpa的实现厂家 -->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property> <!-- jpa的供应适配器 -->
<property name="jpaVendorAdapter">
<bean class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="false" />
<!-- 指定数据库类型 -->
<property name="database" value="MYSQL" />
<!--数据库方言: 支持的特有语法-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
<property name="showSql" value="true"/>
</bean>
</property> <!-- jpa的方言 : 高级的特性 -->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property> </bean> <!--2.创建数据库连接池-->
<bean id = "dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value= "root"/>
<property name="password" value = "root"/>
<property name="jdbcUrl" value="jdbc:mysql:///jpa"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</bean> <!-- 3.整合 spring datajpa -->
<jpa:repositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactoty"></jpa:repositories> <!--4.配置事务管理器-->
<bean id = "transactionManager" class = "org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref = "entityManagerFactoty"></property>
</bean> <!-- 5。声明式事务 --> <!-- 6. 配置包扫描 -->
<context:component-scan base-package="cn.itcast"></context:component-scan>
</beans>

3.实体类添加注解

package cn.itcast.domain;

import javax.persistence.*;

/**
* 客户的实体类
* 配置映射关系
* 1.实体类和表的映射关系
* 2.实体类中属性和表中字段的映射关系
* @Entity:声明实体类
* @Table:配置实体类和表的映射关系
* name:配置数据库表的名称
*/ @Entity
@Table(name = "cst_customer")
public class Customer { /**
* @Id:声明主键的配置
* @GeneratedValue:配置主键的生成策略
* strategy
* GenerationType.IDENTITY:自增,mysql
* *底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
* GenerationType.SEQUENCE:序列,oracle
* *底层数据库必须支持序列
* GenerationType.TABLE :jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
* GenerationType.AUTO :有程序自动的帮助我们选择主键生成策略
* @Column:配置属性和字段的映射关系
* name:数据库表中字段的名称
*/ @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cust_id")
private long custId;//客户的主键 @Column(name = "cust_name")
private String custName;//客户名称 @Column(name = "cust_source")
private String custSource;//客户来源 @Column(name = "cust_level")
private String custLevel;//客户级别 @Column(name = "cust_industry")
private String custIndustry;//客户所属行业 @Column(name = "cust_phone")
private String custPhone;//客户的联系方式 @Column(name = "cust_address")
private String custAddress;//客户地址 public long getCustId() {
return custId;
} public void setCustId(long custId) {
this.custId = custId;
} public String getCustName() {
return custName;
} public void setCustName(String custName) {
this.custName = custName;
} public String getCustSource() {
return custSource;
} public void setCustSource(String custSource) {
this.custSource = custSource;
} public String getCustLevel() {
return custLevel;
} public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
} public String getCustIndustry() {
return custIndustry;
} public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
} public String getCustPhone() {
return custPhone;
} public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
} public String getCustAddress() {
return custAddress;
} public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
} @Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName='" + custName + '\'' +
", custSource='" + custSource + '\'' +
", custLevel='" + custLevel + '\'' +
", custIndustry='" + custIndustry + '\'' +
", custPhone='" + custPhone + '\'' +
", custAddress='" + custAddress + '\'' +
'}';
}
}

4.编写Dao接口

package cn.itcast.dao;

import cn.itcast.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query; import java.util.List; /**
* 符合SpringDataJpa的dao层接口规范
* JpaRepository<操作的实体类类型,实体类中主键的类型>
* *封装了基本CRUD操作
* JpaSpecificationExecutor<操作的实体类类型>
* *封装了复杂查询(分页)
*/
public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> { /**
* 案列:根据客户名称查询客户
* 使用jpql的形式查询
* jpql:from Customer where custName = ?
*
* 配置jpql语句,使用的@Query注解
*/
@Query(value = "from Customer where custName = ?")
public Customer findJpql(String custName); /**
* 案列:根据客户名称和客户id查询客户
* jpql: from Customer where custName = ? and custId = ?
*
* 对于多个占位符参数
* 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
*
* 可以指定占位符参数的位置
* ?索引的方式,指定此占位的取值来源
*/
@Query(value = "from Customer where custName = ?2 and custId = ?1")
public Customer findCustNameAndId(Long id, String name); /**
* 使用jpql完成更新操作
* 案例:根据id更新客户的名称
* 更新4好客户的名称,将名称改为“黑马程序员”
* sql :update cst_customer set cust_name = ? where cust_id = ?
* jpql :update Customer set custName = ? where custId = ?
*
* @Query:代表的时进行查询
* *声明次方法时用来进行更新操作
* @Modifying
* *当前执行的是一个更新操作
*/
@Query(value = "update Customer set custName = ?2 where custId = ?1")
@Modifying
public void updateCustomer(long custId, String custName); /**
*使用sql的形式查询
* 查询全部的客户
* sql:select * from cst_customer
* Query:配置sql查询
* value : sql语句
* nativeQuery : 查询方式
* true:sql查询
* false:jpql查询
* @return
*/
// @Query(value = "select * from cst_customer", nativeQuery = true)
@Query(value = "select * from cst_customer where cust_name like ?1", nativeQuery = true)
public List<Object []> findSql(String name); /**
* 方法名的约定
* findBy :查询
* 对象中的属性名(首字母大写):查询的条件
* CustName
* *默认情况:使用等于的方式查询
* 特殊的查询方式
*
* FindByCustName -- 根据客户名称查询
*
* 在springdataJpa的运行阶段
* 会根据方法名称进行解析 findBy from xxx(实体类)
* 属性名称 where custName =
* 1.findBy + 属性名称(根据属性名称精选完成匹配的查询=
* 2.findBy + 属性名称 + ”查询方式(Like | isnull)"
* findByCustNameLike
* 3.多条件查询
* findBy + 属性名称 + “查询方式” + “多条件的连接符(and | or)” + 属性名 + “查询方式"
*/
public Customer findByCustName(String custName); public List<Customer> findByCustNameLike(String custName); //使用客户名称模糊匹配和客户所属行业精准匹配的查询
public Customer findByCustNameLikeAndCustIndustry(String custName, String custIndustry);
}

5.测试用例

package cn.itcast.test;

import cn.itcast.dao.CustomerDao;
import cn.itcast.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class CustomerDaoTest {
@Autowired
private CustomerDao customerDao; /**
* 根据id查询
*/
@Test
public void testFindOne(){
Customer customer = customerDao.findOne(3L);
System.out.println(customer);
} /**
* sava : 保存或者更新
* 根据传递的对象是否存在主键id,
* 如果没有id主键属性:保存
* 存在id主键属性,根据id查询数据,更新数据
*/
@Test
public void testSave() {
Customer customer = new Customer();
customer.setCustName("黑马程序员");
customer.setCustLevel("vip");
customer.setCustIndustry("it教育");
customerDao.save(customer);
} @Test
public void testUpdate() {
Customer customer = new Customer();
customer.setCustId(4l);
customer.setCustName("黑马程序员很厉害");
customerDao.save(customer);
} @Test
public void testDelete() {
customerDao.delete(3L);
} @Test
public void testFindAll() {
List<Customer> list = customerDao.findAll();
for (Customer customer : list) {
System.out.println(customer);
}
} /**
* 测试统计查询:查询客户的总数量
* cont:统计总条数
*/
@Test
public void testCount() {
long count = customerDao.count();//查询全部的客户数量
System.out.println(count);
} /**
* 测试:判断id为4的客户是否存在
* 1.可以查询一下id为4的客户
* 如果值为空,代表不存在,如果部位空,代表存在
* 2.判断数据库中id为4的客户的数量
* 如果数量为0,代表不存在,如果大于0,代表存在
*/
@Test
public void testExists() {
boolean exists = customerDao.exists(4l);
System.out.println("id为4的客户是否存在:" + exists);
} /**
* 根据id从数据库查询
* @Transactional:保证getOne正常运行
*
* findOne:
* em.find() :立即加载
* getOne:
* em.getReference :延迟加载
* *返回的时客户的动态代理对象
* *什么时候用,什么时候查询
*/
@Test
@Transactional
public void testGetOne() {
Customer customer = customerDao.getOne(4l);
System.out.println(customer);
}
}

JPQL测试用例

package cn.itcast.test;

import cn.itcast.dao.CustomerDao;
import cn.itcast.domain.Customer;
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.Arrays;
import java.util.List; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")//指定spring容器的配置信息
public class JpqlTest {
@Autowired
private CustomerDao customerDao; @Test
public void testFindJPQL() {
Customer customer = customerDao.findJpql("传智播客");
System.out.println(customer);
} @Test
public void testFindCustNameAndId() {
Customer customer = customerDao.findCustNameAndId(1L, "传智播客");
System.out.println(customer);
} /**
* 测试jpql的更新操作
* *springDataJpa中使用jpql完成 更新/删除操作
* *需要手动添加事务的支持
* *默认会执行结束之后,回滚事务
* @Rollback:设置是否自动回滚
* false | true
*/
@Test
@Transactional//添加事务的支持
@Rollback(value = false)
public void testUpdateCustomer() {
customerDao.updateCustomer(4L, "黑马程序员");
} //测试sql查询
@Test
public void testFindSql() {
List<Object[]> list = customerDao.findSql("传智播客%");
for (Object[] obj : list) {
System.out.println(Arrays.toString(obj));
}
} //测试方法命名规则的查询
@Test
public void testNaming() {
Customer customer = customerDao.findByCustName("传智播客");
System.out.println(customer);
} //测试方法命名规则的查询
@Test
public void testFindByCustNameLike() {
List<Customer> list = customerDao.findByCustNameLike("传智播客%");
for (Customer customer : list) {
System.out.println(customer);
}
} //测试方法命名规则的查询
@Test
public void testFindByCustNameLikeAndCustIndustry() {
Customer customer = customerDao.findByCustNameLikeAndCustIndustry("传智播客%", "it教育");
System.out.println(customer);
}
}

如果觉得有收获,不妨花个几秒钟点个赞,欢迎关注我的公众号玩编程地码农,目前专注于写java相关、数据结构与算法和计算机基础等。

Spring Data JPA基本增删改查和JPQL查询(含完整代码和视频连接)

上一篇:Groovy语言学习--语法基础(4)


下一篇:SHA-1 加密算法破解现已只需要 10 天