JPA---Spring-data-JPA---Hibernate
2021-01-24 10:13
标签:创建表 varchar over splay pac code 实现类 pos 保存 版本---maven 3.6.3 Spring Data JPA是spring提供的一款对于数据访问层(Dao层)的框架,使用Spring Data JPA,只需要按照框架的规范提供dao接口,不需要实现类就可以完成数据库的增删改查、分页查询等方法的定义,极大的简化了我们的开发过程。 在Spring Data JPA中,对于定义符合规范的Dao层接口,我们只需要遵循以下几点就可以了: 1.创建一个Dao层接口,并实现JpaRepository和JpaSpecificationExecutor 2.提供相应的泛型
* 对于多个占位符参数
* 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
*
* 可以指定占位符参数的位置
* ? 索引的方式,指定此占位的取值来源
完成了Spring Data JPA的环境搭建,并且编写了符合Spring Data JPA 规范的Dao层接口之后,就可以使用定义好的Dao层接口进行客户的基本CRUD操作 顾名思义,方法命名规则查询就是根据方法的名字,就能创建查询。只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。Spring Data JPA在程序执行的时候会根据方法名称进行解析,并自动生成查询语句进行查询 按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。 //方法命名方式查询(根据客户名称查询客户) public Customer findByCustName(String custName); 具体的关键字,使用方法和生产成SQL如下表所示 Keyword Sample JPQL And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2 Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2 Is,Equals findByFirstnameIs, findByFirstnameEquals … where x.firstname = ?1 Between findByStartDateBetween … where x.startDate between ?1 and ?2 LessThan findByAgeLessThan … where x.age
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1 GreaterThan findByAgeGreaterThan … where x.age > ?1 GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1 After findByStartDateAfter … where x.startDate > ?1 Before findByStartDateBefore … where x.startDate
IsNull findByAgeIsNull … where x.age is null IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null Like findByFirstnameLike … where x.firstname like ?1 NotLike findByFirstnameNotLike … where x.firstname not like ?1 StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %) EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %) Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %) OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc Not findByLastnameNot … where x.lastname ?1 In findByAgeIn(Collection ages) … where x.age in ?1 NotIn findByAgeNotIn(Collection age) … where x.age not in ?1 TRUE findByActiveTrue() … where x.active = true FALSE findByActiveFalse() … where x.active = false IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1) Spring Data JPA--搭建环境
导入依赖坐标
dependencies>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-aopartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.aspectjgroupId>
artifactId>aspectjweaverartifactId>
version>1.9.5version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-contextartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-context-supportartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-testartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-ormartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-beansartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-coreartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>org.hibernategroupId>
artifactId>hibernate-entitymanagerartifactId>
version>${hibernate.version}version>
dependency>
dependency>
groupId>org.hibernategroupId>
artifactId>hibernate-coreartifactId>
version>${hibernate.version}version>
dependency>
dependency>
groupId>org.hibernate.validatorgroupId>
artifactId>hibernate-validatorartifactId>
version>6.1.2.Finalversion>
exclusions>
exclusion>
artifactId>classmateartifactId>
groupId>com.fasterxmlgroupId>
exclusion>
exclusions>
dependency>
dependency>
groupId>mysqlgroupId>
artifactId>mysql-connector-javaartifactId>
version>${mysql.version}version>
dependency>
dependency>
groupId>com.alibabagroupId>
artifactId>druidartifactId>
version>${druid.version}version>
dependency>
dependency>
groupId>org.springframework.datagroupId>
artifactId>spring-data-jpaartifactId>
version>2.2.6.RELEASEversion>
exclusions>
exclusion>
artifactId>slf4j-apiartifactId>
groupId>org.slf4jgroupId>
exclusion>
exclusions>
dependency>
dependency>
groupId>org.springframeworkgroupId>
artifactId>spring-testartifactId>
version>${spring.version}version>
dependency>
dependency>
groupId>javax.elgroupId>
artifactId>javax.el-apiartifactId>
version>3.0.0version>
dependency>
dependency>
groupId>org.glassfishgroupId>
artifactId>javax.elartifactId>
version>3.0.0version>
dependency>
dependency>
groupId>org.slf4jgroupId>
artifactId>slf4j-apiartifactId>
version>${slf4j.version}version>
dependency>
dependency>
groupId>org.apache.logging.log4jgroupId>
artifactId>log4j-apiartifactId>
version>${log4j.version}version>
dependency>
dependency>
groupId>junitgroupId>
artifactId>junitartifactId>
version>4.12version>
dependency>
dependencies>
创建配置文件
applicatioContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:contxt="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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
property name="dataSource" ref="dataSource"/>
property name="packagesToScan" value="com.ytfs.entity"/>
property name="persistenceProvider">
bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
property>
property name="jpaVendorAdapter">
bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
property name="showSql" value="true"/>
property name="database" value="MYSQL"/>
property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
property name="generateDdl" value="false"/>
bean>
property>
bean>
contxt:property-placeholder location="classpath:jdbcConfig.properties"/>
bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
property name="username" value="${jdbc.username}"/>
property name="driverClassName" value="${jdbc.driver}"/>
property name="url" value="${jdbc.url}"/>
property name="password" value="${jdbc.password}"/>
bean>
bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
property name="entityManagerFactory" ref="entityManagerFactory"/>
bean>
jpa:repositories base-package="com.ytfs.dao"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
context:component-scan base-package="com.ytfs"/>
jdbcConfig.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jpa
jdbc.username=root
jdbc.password=root
创建实体类
package com.ytfs.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* @Classname Customer
* @Description TODO(客户实体类)
* @Date 2020/4/29 21:34
* @Created by ytfs
*/
@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cust_id")
private Long custId;
/**
* cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT ‘客户编号(主键)‘,
* `cust_name` varchar(32) NOT NULL COMMENT ‘客户名称(公司名称)‘,
* `cust_source` varchar(32) DEFAULT NULL COMMENT ‘客户信息来源‘,
* `cust_industry` varchar(32) DEFAULT NULL COMMENT ‘客户所属行业‘,
* `cust_level` varchar(32) DEFAULT NULL COMMENT ‘客户级别‘,
* `cust_address` varchar(128) DEFAULT NULL COMMENT ‘客户联系地址‘,
* `cust_phone` v
*/
@Column(name = "cust_name")
private String custName;
@Column(name = "cust_source")
private String custSource;
@Column(name = "cust_industry")
private String custIndustry;
@Column(name = "cust_level")
private String custLevel;
@Column(name = "cust_address")
private String custAddress;
@Column(name = "cust_phone")
private String custPhone;
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 getCustIndustry() {
return custIndustry;
}
public void setCustIndustry(String custIndustry) {
this.custIndustry = custIndustry;
}
public String getCustLevel() {
return custLevel;
}
public void setCustLevel(String custLevel) {
this.custLevel = custLevel;
}
public String getCustAddress() {
return custAddress;
}
public void setCustAddress(String custAddress) {
this.custAddress = custAddress;
}
public String getCustPhone() {
return custPhone;
}
public void setCustPhone(String custPhone) {
this.custPhone = custPhone;
}
@Override
public String toString() {
return "Customer{" +
"custId=" + custId +
", custName=‘" + custName + ‘\‘‘ +
", custSource=‘" + custSource + ‘\‘‘ +
", custIndustry=‘" + custIndustry + ‘\‘‘ +
", custLevel=‘" + custLevel + ‘\‘‘ +
", custAddress=‘" + custAddress + ‘\‘‘ +
", custPhone=‘" + custPhone + ‘\‘‘ +
‘}‘;
}
}
创建dao接口
package com.ytfs.dao;
import com.alibaba.druid.sql.visitor.functions.If;
import com.ytfs.entity.Customer;
import org.hibernate.mapping.Value;
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.lang.invoke.VarHandle;
import java.security.spec.NamedParameterSpec;
import java.util.List;
/**
* @Classname CustomerDao
* @Description TODO(客户的数据库访问层)
* @Date 2020/4/29 21:46
* @Created by ytfs
* JpaRepository:用来完成基本CRUD操作
* JpaSpecificationExecutor:用于复杂查询(分页等查询操作)
*/
public interface CustomerDao extends JpaRepository
创建spring-data-jpa的测试案例
package com.ytfs.test;
import com.ytfs.dao.CustomerDao;
import com.ytfs.entity.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 java.util.List;
/**
* @Classname SpringDataJpaTest
* @Description TODO(springDataJpa的测试案例)
* @Date 2020/4/29 21:58
* @Created by ytfs
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringDataJpaTest {
@Autowired
private CustomerDao customerDao;
/**
* @description 查询全部
* @author 雨听风说
* @updateTime 2020/4/29 22:44
*/
@Test
public void testFindALl() {
List
JPQL
1.1 方法命名规则查询
创建JPQL的测试案例
package com.ytfs.test;
import com.ytfs.dao.CustomerDao;
import com.ytfs.entity.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 javax.transaction.Transactional;
import java.util.List;
/**
* @Classname SpringDataJPAJpqlTest
* @Description TODO(SpringDataJpaJpql测试)
* @Date 2020/4/30 21:15
* @Created by ytfs
*/
/**
* jpql的查询方式
* jpql : jpa query language (jpq查询语言)
* 特点:语法或关键字和sql语句类似
* 查询的是类和类中的属性
* 需要将JPQL语句配置到接口方法上
* 1.特有的查询:需要在dao接口上配置方法
* 2.在新添加的方法上,使用注解的形式配置jpql查询语句
* 3.注解 : @Query
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringDataJPAJpqlTest {
@Autowired
private CustomerDao customerDao;
/**
* @description 通过JPQL的方式查询所有的客户
* @author 雨听风说
* @updateTime 2020/4/30 21:48
*/
@Test
public void testFindAll() {
List
文章标题:JPA---Spring-data-JPA---Hibernate
文章链接:http://soscw.com/essay/46265.html