SpringDataJPA之快速入门

  Spring Data JPA:Spring Data JPA 是 spring data 项目下的一个模块。提供了一套基于 JPA标准操作数据库的简化方案。底层默认的是依赖 Hibernate JPA 来实现的。
  Spring Data JPA 的技术特点:我们只需要定义接口并集成 Spring Data JPA 中所提供的接口就可以了。不需要编写接口实现类。

SpringDataJPA

一、接口继承结构

  在搭建入门案例之前我们先来看下SpringDataJPA中所需要使用到的几个接口的继承结构图,便于我们后面的分析。

SpringDataJPA之快速入门_第1张图片

二、入门案例

  我们先通过JpaRepoistry接口来快速实现一个添加操作

1.创建maven项目

  创建一个简单的maven项目即可

2.添加相关依赖

  基础依赖和前面介绍的hibernateJPA是一样的,额外再添加SpringDataJPA的依赖即可,具体如下:

<dependencies>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.6.8.RELEASEversion>
    dependency>
    <dependency>
        <groupId>com.mchangegroupId>
        <artifactId>c3p0artifactId>
        <version>0.9.5.3version>
    dependency>
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-coreartifactId>
        <version>5.0.7.Finalversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-ormartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.32version>
    dependency>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>4.3.21.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-entitymanagerartifactId>
        <version>5.0.7.Finalversion>
    dependency>
    <dependency>
        <groupId>org.springframework.datagroupId>
        <artifactId>spring-data-jpaartifactId>
        <version>1.9.0.RELEASEversion>
    dependency>
dependencies>

3.添加配置文件

  一个数据库的配置文件及spring的配置文件,注意添加jps的schema。如下:

jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=123456

<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/data/jpa
	http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	
	<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>

	
	<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">
				
				
				<property name="database" value="MYSQL"/>
				
				<property name="generateDdl" value="true"/>
				
				<property name="showSql" value="true"/>
			bean>
		property>
		
		<property name="packagesToScan">
			<list>
				<value>com.dpb.pojovalue>
			list>
		property>
	bean>
	
	<bean id="transactionManager"
		  class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory"
				  ref="entityManagerFactory"/>
	bean>
	
	
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	
	<context:component-scan base-package="com.dpb"/>

	
	
	<jpa:repositories base-package="com.dpb.dao"/>
beans>

4.创建pojo和Dao接口

  创建pojo类Users和Dao接口如下:

package com.dpb.pojo;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @program: spring-hibernate-jpa
 * @description: Users的Pojo对象
 * @author: 波波烤鸭
 * @create: 2019-05-18 09:37
 */

@Entity
@Table(name="users")
public class Users implements Serializable {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)//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 + "]";
    }

}

/**
 * SpringDataJPA 实现JpaRepository
 * 泛型 第一个参数是对应的Pojo类型
 *      第二个参数是注解的包装类型
 */
public interface UserDao extends JpaRepository<Users,Integer> {

}

5.单元测试


/**
 * @program: spring-data-jpa
 * @description: 单元测试
 * @author: 波波烤鸭
 * @create: 2019-05-18 09:48
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {

    @Autowired
    private UserDao usersDao;


    /**
     * 添加用户
     */
    @Test
    @Transactional// 在测试类对于事务提交方式默认的是回滚。
    @Rollback(false)//取消自动回滚
    public void testInsertUsers(){
        Users users = new Users();
        users.setUserage(20);
        users.setUsername("张三-jpa");
        this.usersDao.save(users);
    }
}

SpringDataJPA之快速入门_第2张图片

你可能感兴趣的:(#,SPRING-DATA系列)