SpingData Jpa的配置和常用操作

SpringData Jpa 的入门操作

  1. 导入坐标
<dependencies>
<!--  单元测试  -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
<!--  hibernate 依赖     -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.7.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.7.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

<!--  springdata 依赖 -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.1.4.RELEASE</version>
        </dependency>
<!-- el 依赖  使用springdata  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>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.7.RELEASE</version>
        </dependency>
    </dependencies>
<?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">
    <!-- 6. 配置包扫描-->
    <context:component-scan base-package="com.ahead" ></context:component-scan>
    <!--spring 和 spring data jpa的配置-->

    <!-- 1.创建entityManagerFactory对象交给spring容器管理-->
    <bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--配置的扫描的包(实体类所在的包) -->
        <property name="packagesToScan" value="com.ahead.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>
        <property name="password" value="123456"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" ></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    </bean>

    <!--3.整合spring dataJpa-->
    <jpa:repositories base-package="com.ahead.dao" transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories>

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

    <!-- 4.txAdvice-->
<!--
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

     5.aop
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* cn.ahead.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    -->

    <!--5.声明式事务 -->


</beans>
  1. 编写一个符合springdataJpa的dao 接口
  2. 只需要编写dao层接口,不需要编写dao层的实现类
  3. dao层接口规范:
    1 需要继承两个接口(JpaRepository,JpaSpecificationExecutor)
    2 需要提供响应的泛型
public interface CustomerDao extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer> {}

一些基于jpa提供增删查改

package com.ahead.test;

import com.ahead.dao.CustomerDao;
import com.ahead.domain.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 org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@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(2);
        System.out.println(customer);
    }
    /*
     * 查询所有用户 根据主键查询
     * 结果  所有用户
     * */
    @Test
    public void testFindAll() {
        List<Customer> list  = customerDao.findAll();
        for (Object obj : list) {
            System.out.println(obj.toString());
        }
    }

    /*
     * 保存或者更新用户
     *  如果设置的主键在数据库中不存在则会保存用户,并且会将主键值设置为(表中主键最大的数值+1)
     * */
    @Test
    public void save() {
        Customer customer=new Customer();
        customer.setId(8);
        customer.setName("小朋友");
        customer.setAddress("江西南昌");
        customer.setEmail("ahosh@qq.com");
        customer.setTel("1224435342");
        customer.setCreateDate(new Date());
        customerDao.save(customer);
    }
    /*
    * 获取数据库中数据的数量
    * */
    @Test
    public void testConunt(){
        long count = customerDao.count();
        System.out.println(count);
    }
    /*
     *根据用户Id从数据库查询
     *   Transactional:保证getOne正常运行(如果不添加会执行异常)
     *
     * findOne() : 底层用的是em.find()方法   立即加载
     * getOne() : 底层用的是em.getReference;  延迟加载
     * */
    @Test
    @Transactional
    public void testGetone(){
        Customer customer = customerDao.getOne(2);
        System.out.println(customer);

    }

}

SpringData 整合jpa的一些增删查改方法

@Query注解查询适用于所查询的数据无法通过关键字查询得到结果的查询。这种查询可以摆脱像关键字查询那样的约束,将查询直接在相应的接口方法中声明,结构更为清晰,这是Spring Data的特有实现。


/**
 *   JpaRepository<操作的实体类类型, 实体类主键的类型>
 *       封装了基本的CRUD操作
 *   JpaSpecificationExecutor<操作的实体类类型>
 *       封装了复杂的查询(分页查询)
 *
 *   方法名称规则查询
 *      是对jpql查询,更加深入的一层封装,我们只需要按照springdata Jpa 提供的方法名称规则定义方法,
 *      不需要再去配置jpql语句,完成查询
 */

public interface CustomerDao extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer> {
   /*
   * 对于传入多个参数是可以指定参数占位符的位置 eg:
   *  from Customer(daomain中的名字) where name = ? 1 and id =? 2  (数字表明顺序(形式参数的顺序))
   * */
    @Query(value = "from Customer where name =  ?  and id= ?")
    public   Customer findByName(String name,int id);
    /*
    * 更新操作
    * */
    @Query(value = "update Customer set name = ? where id =?")
    @Modifying//这个注解是通知jpa当前操作是删除/更新,不添加会抛异常
    public Integer  updateDemo(String name ,int id );
    /*
    * 查询全部
    * */
//    @Query(value = "select * from Customer ")
//    public List<Customer> selectAll( );
    /*
    * 条件查询
    *   @Query有两个参数  一个是value(根据nativeQuery的值来写jpql语句还是sql语句)
    *                     一个是nativeQuery(默认是false) :false(使用jpql语句查询)  true(使用sql语句查询)
    *
    * */
    @Query(value = "select * from custorm where name like ?",nativeQuery = true)
    public List<Object[]> selectCondition(String name);

    /*
    * 方法名的约定
    *    findBy : 查询
    *         后面接的是对象中的属性名(首字母大写)--> 查询条件
    *  组合起来:findByName  根据名字来查询用户信息
    *  流程图是 :springdata jpa 在运行阶段会根据方法名称进行解析
    *  findBy --->  from  xxx(实体类名称) where  (查询条件)name =? ;这样的一个jpql语句。
    *
    * 多条件查询
    *  findBy +属性名+ +“查询方式”+ “多条件的连接符(and|or)”+属性名+ “查询方式”
    * */
    public Customer findByName(String name);

    //通过name的模糊查询和地址的精准匹配
    public List<Customer> findByNameLikeAndAddress(String name,String address);

基于注解@Query常用操作测试类

@RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试
@ContextConfiguration(locations = "classpath:applicationContext.xml") //指定spring容器配置信息
public class JpqlTest {
    @Autowired
    private CustomerDao customerDao;

    @Test
    public void testJpql(){
        Customer customer = customerDao.findByName("小朋友",5);
        System.out.println(customer);
    }
    @Test
    @Transactional//必须添加事物,不然会导致异常
    /*
    * 视频上说的是不加这个注解的话会自动回滚,但是我的案例不会出现这个原因,不知道啥情况
    * 而且设置true和false都不会回滚,都能直接操作成功数据库中的数据
    * */
    @Rollback(value = false)
    public void testJpqlUpdate(){
        Integer demo = customerDao.updateDemo("天Kong翼间", 2);
    }
    /*
    * 查询全部
    * */
//    @Test
//    public void selectAll(){
//       List<Customer> customerList= customerDao.selectAll();
//        for (Object object:customerList) {
//            System.out.println(object.toString() );
//        }
//    }
    /*
     * 查询全部
     * */
    @Test
    public void selectByCondition(){
       List<Object[]>  customerList= customerDao.selectCondition("邓%");
        for (Object[]  object:customerList) {
            System.out.println(Arrays.toString(object) );
        }
    }
}

方法名称规则查询测试类

@RunWith(SpringJUnit4ClassRunner.class)//声明spring提供的单元测试
@ContextConfiguration(locations = "classpath:applicationContext.xml") //指定spring容器配置信息
public class rulesJpqlTest {
    @Autowired
    private CustomerDao customerDao;

    @Test
    public  void findByNameTets(){
        Customer customer = customerDao.findByName("邓超");
        System.out.println(customer);
    }
    @Test
    public  void findMoreCondition(){
        List<Customer> customer = customerDao.findByNameLikeAndAddress("邓%","北京市大兴区");
        for (Customer customer1 : customer) {
            System.out.println(customer1);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值