springdatajpa
1.它是JPA规范的再次封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL的查询语句 ,是属于Spring的生成体系中的一部分
//Spring Data JPA的七个Repository接口:
Repository(org.springframework.data.repository.Repository)
CrudRepository(org.springframework.data.repository.CrudRepository)
PagingAndSortingRepository(org.springframework.data.repository.PagingAndSortingRepository)
JpaRepository (org.springframework.data.jpa.repository.JpaRepository)
QueryByExampleExecutor(org.springframework.data.repository.query.QueryByExampleExecutor)
JpaSpecificationExecutor (org.springframework.data.jpa.repository.JpaSpecificationExecutor)
QueryDslPredicateExecutor (org.springframework.data.querydsl.QueryDslPredicateExecutor)
两大Repository实现类:
SimpleJpaRepository(org.springframework.data.jpa.repository.support.SimpleJpaRepository)
QueryDslJpaRepository(org.springframework.data.jpa.repository.support.QueryDslJpaRepository)
springdatajpa结构图
2.新建一个接口继承jpaRepository,springdatajpa底层会通过动态代理的方式创建新建接口的动态代理对象,并且拥有底层实现类中的所有方法(SimpleJpaRepository)
3.分页和排序,curd
//普通CURD
@Test
public void testFindAll() throws Exception{
List<Employee> emps = employeeRepository.findAll();
for (Employee emp :emps){
System.out.println(emp);
}
}
//根据id到一条数据
@Test
public void testFindOne() throws Exception{
Employee employee = employeeRepository.findOne(1L);
System.out.println(employee);
}
//添加与修改都使用save(主要看对象有没有id)
@Test
public void testSave() throws Exception{
Employee employee = new Employee();
//employee.setId(103L);
employee.setUsername("张三");
employee.setPassword("1234");
employee.setEmail("zhangsha@163.com");
employeeRepository.save(employee);
}
//删除数据
@Test
public void testDelete() throws Exception{
employeeRepository.delete(103L);
}
//得到总条数
@Test
public void testCount(){
System.out.println(employeeRepository.count());
}
//进行分页功能
@Test
public void testPage() {
//1.需要先创建一个page对象(注意:页数是从0开始计算【0就是第1页】)
Pageable pageable = new PageRequest(0, 10);
//2.进行查询
Page<Employee> page = employeeRepository.findAll(pageable);
System.out.println(page.getTotalElements()); //总条数
System.out.println(page.getTotalPages()); //总页数
System.out.println(page.getContent()); //当前页数据
System.out.println(page.getNumber()); //第几页
System.out.println(page.getNumberOfElements()); //当前页有多少个数据
System.out.println(page.getSize()); //每页条数
}
//进行排序功能
@Test
public void testSort() {
//排序 :第一个参数是排序的规则(DESC/ASC) 后面参数是排序的字符
Sort sort = new Sort(Sort.Direction.DESC,"username");
List<Employee> emps = employeeRepository.findAll(sort);
for (Employee emp : emps) {
System.out.println(emp);
}
}
//分页与排序的集成
@Test
public void testPageAndSort() {
//排序 :第一个参数是排序的规则(DESC/ASC) 后面参数是排序的字符
Sort sort = new Sort(Sort.Direction.DESC,"username");
Pageable pageable = new PageRequest(0, 10,sort);
//2.进行查询
Page<Employee> page = employeeRepository.findAll(pageable);
for (Employee employee : page) {
System.out.println(employee);
}
}
4.jpql查询
根据参数顺序
@Query("select o from Employee o where o.username like ?1 and o.email like ?2")
List<Employee> query02(String username,String email);
根据参数名称
@Query("select o from Employee o where o.username like :username and o.email like :email")
List<Employee> query03(@Param("username") String username,@Param("email") String email);
//原生sql查询
@Query(value="SELECT COUNT(*) FROM employee",nativeQuery = true)
Long queryCount();
5.jpa-spec条件查询
<!-- 引入依赖 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有依赖都过滤 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
//多条件查询
@Test
public void testSpecFind02() {
Specification<Employee> spec = Specifications.<Employee>and().like("username", "%1%")
.like("email","%2%").lt("age", 20).build();
List<Employee> emps = employeeRepository.findAll(spec);
for (Employee emp : emps) {
System.out.println(emp);
}
}
5.环境搭建
pom.xml
<!-- hibernate的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<!-- SpringData的支持包 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<!-- SpringData的擴展包 -->
<dependency>
<groupId>com.github.wenhao</groupId>
<artifactId>jpa-spec</artifactId>
<version>3.1.1</version>
<!-- 把所有的依賴都去掉 -->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.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
">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.wal.springdata.domain"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--扫描@Transaction注解-->
<tx:annotation-driven/>
<!--配置springdata 引入jpa事务和jpa实体工厂-->
<jpa:repositories base-package="com.wal.springdata.repository"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- 加上OpenEntityManager -->
//解决懒加载时事务提前关闭的问题
//必须配置在核心控制器之前
<filter>
<filter-name>openEntity</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openEntity</filter-name>
<url-pattern>\/*</url-pattern>
</filter-mapping>
//加载applicationcontext.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationcontext.xml</param-value>
</context-param>
<!--启动Spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>\/*</url-pattern>
</filter-mapping>
//核心控制器
<servlet>
<servlet-name>dispatcheServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationcontext-mvc.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcheServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>