欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的入门springDataJpa

程序员文章站 2022-04-15 23:43:59
...

springDataJpa

  • Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案

  • springDataJpa,jpa,hibernate关系三者的关系
    简单的入门springDataJpa

springDataJpa的入门操作

  1. 搭建环境
    1. 创建工程导入坐标
    2. 配置spring的配置文件 (配置spring Data jpa的整合)
    3. 编写实体类(Customer),使用jpa注解配置映射关系

  2. 编写一个符合springDataJpa的dao层接口
    * 只需要编写dao层接口,不需要编写dao层接口的实现类
    * dao层接口规范
    1. 需要继承两个接口(JpaRepository, JpaSpecificationExecutor)
    2. 需要提供响应的泛型

  • 常用的方法
    * findOne(id) : 根据id查询 立即加载
    * getOne(id) : 根据id查询 延迟加载
    * save(customer) : 保存或者更新(依据: 传递的实体类对象中,是否包含id属性)
    * delete(id) : 根据id删除
    * findAll() : 查询全部

1.导入的xml坐标

    <properties>
        <spring.version>4.2.4.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.9</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>

2. 配置spring的配置文件applicationContext.xml 在resources目录下

<?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"
       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">

    <!-- spring和 spring data jpa的配置 -->

    <!-- 1. 创建entityManagerFactory对象交给spring容器管理 -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource"  ref="dataSource"/>

        <!-- 配置的扫描的包(实体类所在的包)  -->
        <property name="packagesToScan" value="cn.test.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" />
                <!-- 是否显示sql语句 -->
                <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://localhost:3306/jpa"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </bean>

    <!-- 3.整合spring data jpa -->
    <jpa:repositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"/>

    <!-- 4. 配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    

    <!-- 6. 配置包扫描 -->
    <context:component-scan base-package="cn.test"/>

3. 编写实体类(Customer),使用jpa注解配置映射关系

  • 1.) 用到的数据库表
    简单的入门springDataJpa
  • 2.) 建表语句
/*创建客户表*/
CREATE TABLE cst_customer (
  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 VARCHAR(64) DEFAULT NULL COMMENT '客户联系电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=INNODB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;
  • 3.) 建立实体类
@Entity
@Table(name = "cst_customer")
public class Customer {

    @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; //客户地址

 	//get和set省略
    //toString省略
    
    }
}
  • 注解解释
	@Entity: 声明实体类
	@Table: 配置实体类和表的映射关系
		name: 配置数据库表的名称
			注: 我这里的数据库表名是cst_customer
		
		
	@Id: 声明主键的配置
	@GeneratedValue: 配置主键的生成策略
		strategy
			GenerationType.IDENTITY : 自增	 注: 一般用于mysql数据库
			* 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
			
			GenerationType.SEQUENCE : 序列,  注: 一般用于oracle数据库
			* 注: 一般主要就是用这两种了,另外两种很少用到


	@Column: 配置属性和字段的隐射关系
		name: 代表数据库表中字段的名称
			注: 我这里每个基本都和数据库相对应

编写一个符合springDataJpa的dao层接口

public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
}

注:

	符合springDataJpa的dao层接口规范
       	JpaRepository<操作的实体类类型,实体类中主键属性的类型>
           	* 封装了基本的CRUD操作
       	JpaSpecificationExecutor<操作的实体类类型>
           	* 封装了复杂查询 (分页)

小案例

	@RunWith(SpringJUnit4ClassRunner.class)     //声明spring提供的单元测试环境
@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);
    }
    
 }
  • 除了哪些自带的方法, 还能自己在dao内写复杂的查询.
相关标签: # springDataJpa