Spring Date JPA

介绍

官网:https://spring.io/projects/spring-data-jpa#overview

Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.
Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

Spring Data JPA 是更大的 Spring Data 系列的一部分,可以轻松实现基于 JPA 的repositories。该模块处理对基于 JPA 的数据访 问层的增强支持。它使构建使用数据访问技术的 Spring 驱动的应用程序变得更加容易。 实现应用程序的数据访问层已经很麻烦了。必须编写太多样板代码来执行简单的查询以及执行分页和审计。Spring Data JPA 旨在改 进数据访问层的实现以提升开发效率。作为开发人员,您编写存储库接口,包括自定义 finder 方法,Spring 将自动提供实现。

翻译成人话
spirng data jpa是spring提供的一套简化JPA开发的框架,按照约定好的规则进行【方法命名】去写dao层接口,就可以 在不写接口实现的情况下,实现对数据库的访问和操作。同时提供了很多除了CRUD之外的功能,如分页、排序、复杂查 询等等。

Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使 用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使 数据库层操作更加简单,方便解耦

特性

在这里插入图片描述
SpringData Jpa 极大简化了数据库访问层代码。 如何简化的呢? 使用了SpringDataJpa,我们的dao层中只需要写接
口,就自动具有了增删改查、分页查询等方法

在这里插入图片描述
Spring Data JPA实例

我们来实现一个基于Spring Data JPA的示例感受一下和之前单独使用的区别:
依赖
1.最好在父maven项目中设置spring data统一版本管理依赖: 因为不同的spring data子项目发布时间版本不一样,你自 己维护很麻烦, 这样不同的spring data子项目能保证是统一版本.

在这里插入图片描述
2.在子项目中添加:

在这里插入图片描述
在这里插入图片描述
JavaConfig

@Configuration
@EnableJpaRepositories("com.tuling.repository")
@EnableTransactionManagement
public class JpaConfig {
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource(); dataSource.setUsername("root"); dataSource.setPassword("123456"); dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springdata_jpa"); return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true); vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("com.tuling.pojo"); factory.setDataSource(dataSource());
return factory;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory); return txManager;
}
}

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/tas k"
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">

	<!‐‐ 1.dataSource 配置数据库连接池‐‐>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
<property name="user" value="root" />
<property name="password" value="111111" />
</bean>

<!‐‐ 2.配置entityManagerFactory ‐‐>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="cn.itcast.entity" />
<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>
</bean>
<!‐‐ 整合spring data jpa‐‐>
<jpa:repositories base‐package="cn.itcast.dao"
transaction‐manager‐ref="transactionManager" entity‐manager‐factory‐ref="entityManagerFactory"></jpa:repositories>

<!‐‐ 3.事务管理器‐‐>
<!‐‐ JPA事务管理器  ‐‐>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!‐‐基于注解方式的事务,开启事务的注解驱动
如果基于注解的和xml的事务都配置了会以注解的优先
‐‐>
<tx:annotation‐driven transaction‐manager="transactionManager"></tx:annotation‐driven>
<context:component‐scan base‐package="cn.itcast"></context:component‐scan>


<!‐‐组装其它 配置文件‐‐>
</beans>


pojo

package com.tuling.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType; import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO) private Long id;
private String firstName;
private String lastName;
protected Customer() {}

public Customer(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}

@Override
public String toString() { return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}

public Long getId() {
return id;
}

public String getFirstName() { return firstName;
}

public String getLastName() { return lastName;
}

CustomerRepository

public interface CustomerRepository extends CrudRepository<Customer, Long> {
}

// 基于junit4 spring单元测试
//@ContextConfiguration("/spring.xml")
@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringdataJpaTest {

@Autowired
CustomerRepository repository;

@Test
public void testR(){
Optional<Customer> byId = repository.findById(1L);

System.out.println(byId.get());
}

@Test
public void testC(){


Customer customer = new Customer();
customer.setCustId(3L);
customer.setCustName("李四");

repository.save(customer);
}

@Test
public void testD(){


Customer customer = new Customer();
customer.setCustId(3L);
customer.setCustName("李四");

repository.delete(customer);
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值