jpa-数据操作

官方文档:Spring Data JPA - Reference Documentation

1、继承类CrudRepository或者PagingAndSortingRepository

import org.springframework.data.repository.CrudRepository;

public interface CustomerRepository extends CrudRepository<Customer,Long> {

}

2、自定义

1.jpql语言

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface CustomerPagingAndSortingRepository extends PagingAndSortingRepository<Customer, Long> {

    //查询:采用jpql语言
    @Query("FROM Customer where customerName=?1")
    Customer findCustomerByCustomerName(String customerName);

    @Transactional  //增删改都需要加上事务
    @Modifying
    @Query("UPDATE Customer c set c.customerName=:xxx where c.customerId=:id")
    Customer updateCustomer(@Param("xxx") String customerName, @Param("id")Long id);

    //原生的SQl语句
    @Query(value = "select * FROM cst_customer where customerName=?1")
    Customer findCustomerByCustomerNameBySql(String customerName);
}

2.命名规范

find...By

exists...By

count...By

...First<number>... 查找第一条或者前number条

谓词关键字:And Or Is/Equals Like NotLike Not In NotIn

import org.springframework.data.repository.PagingAndSortingRepository;
​
import java.util.List;
​
public interface CustomerRepositoryForName extends PagingAndSortingRepository<Customer, Long> {
​
    List<Customer> findByCustomerName(String customerName);
​
    boolean existsByCustomerNam(String customerName);
    
}

3.query by example 不推荐使用

只适用于字符串的匹配

public interface CustomerQBERepository extends PagingAndSortingRepository<Customer, Long>,QueryByExampleExecutor<Customer> {
}

使用

@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringQBETest {
​
    @Autowired
    CustomerQBERepository repository;
​
    @Test
    public void test1(){
        Customer customer = new Customer();
        customer.setCustomerName("李四");
        customer.setCustomerId(5L);
        //匹配器
        ExampleMatcher matcher=ExampleMatcher.matching().
                withIgnorePaths("customerName").
                withStringMatcher(ExampleMatcher.StringMatcher.ENDING). //全部匹配生效
                withMatcher("",m->m.endsWith())   单个条件匹配生效
                ;
        //样例
        Example<Customer> of = Example.of(customer,matcher);
​
        List<Customer> xx = (List<Customer>) repository.findAll(of);
        System.out.println(xx);
​
    }
}

4.queryDSL 面向Q类

public interface CustomerQUERYDSLRepository extends CrudRepository<Customer,Long>, QuerydslPredicateExecutor<Customer> {
}

使用

// pom需要增加 这里会生成Q类,需要将生成的Q类在项目里面设置成source文件
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>${querydsl.version}</version>  // 采用最新版本即可
        </dependency>
......
<build>
        <plugins>
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <dependencies>
                    <dependency>
                        <groupId>com.querydsl</groupId>
                        <artifactId>querydsl-apt</artifactId>
                        <version>${querydsl.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/queries</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringQUERYDSLTest {
    @Autowired
    CustomerQUERYDSLRepository repository;
    @Test
    public void test1(){
        QCustomer qCustomer = QCustomer.customer;
        BooleanExpression and = qCustomer.customerName.in("李四", "阿姆斯特威廉")
                .and(qCustomer.customerId.gt(1L))   // 大于
                .and(qCustomer.customerAddress.eq("三国"));
        Optional<Customer> one = repository.findOne(and);
    }
}

5.Specification

public interface CustomerSpecificationRepository extends PagingAndSortingRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringSpecificationTest {
​
    @Autowired
    CustomerSpecificationRepository repository;
    
    @Test
    public void test2() {
        List<Customer> all = repository.findAll(new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                //获取类的参数
                Path<Object> customerId = root.get("customerId");
                Path<Object> customerName = root.get("customerName");
                Path<Object> customerAddress = root.get("customerAddress");
​
                Predicate p1 = criteriaBuilder.equal(customerAddress, "刑法课上");  //第一个条件
                Predicate p2 = criteriaBuilder.equal(customerId, 3L);  //第二个条件
                CriteriaBuilder.In<Object> in = criteriaBuilder.in(customerName);
                in.value("张三啊").value("李四");
                Predicate and = criteriaBuilder.and(p1, p2, in);  //与逻辑连接三个条件 ,参与也可以为Predicate数组
//                return p1;
//                return and;
                //排序
                Order desc = criteriaBuilder.desc(customerId);
                return query.where(and).orderBy(desc).getRestriction();
            }
        });
    }
}

6.原生

@ContextConfiguration(classes = SpringJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringSpecificationTest {
​
    @PersistenceContext  //替代@Autowired,解决线程安全问题
    EntityManager em;
​
    @Test
    public void test3() {
        JPAQueryFactory factory = new JPAQueryFactory(em);
​
        QCustomer customer = QCustomer.customer;
        
        // 查询条件
        JPAQuery<Customer> customerJPAQuery = factory.select(customer)
                .from(customer)
                .where(customer.customerId.gt(2L))
                .orderBy(customer.customerId.desc());
        // 执行查询
        List<Customer> fetch = customerJPAQuery.fetch();
​
        for (Customer fetch1 : fetch) {
            System.out.println(fetch1);
        }
    }
​
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
hibernate-jpa-2.1-api 1.0.2是一个Java持久化规范的实现库。它是基于JPA(Java Persistence API)2.1规范的Hibernate实现。Hibernate是一个流行的ORM(对象关系映射)框架,用于在Java应用程序和关系数据库之间进行数据持久化。 该版本的hibernate-jpa-2.1-api是对JPA 2.1规范的实现,并且是Hibernate团队为了确保应用程序与Java EE 7兼容性而发布的一个版本。 JPA是一种使用对象模型操作数据库的标准规范,它提供了一组API,使开发人员可以使用面向对象的方式访问和操作数据库。Hibernate作为一个JPA的实现,提供了许多附加的功能和特性,使得开发人员可以更加简化和灵活地进行数据操作。 通过使用hibernate-jpa-2.1-api,开发人员可以使用JPA的标准API,以及Hibernate提供的独有特性,来实现应用程序的数据持久化需求。它提供了实体管理器,用于管理实体对象的生命周期,以及CRUD操作。此外,它还提供了用于查询和各种持久化注解的支持。 通常情况下,使用hibernate-jpa-2.1-api需要将其添加到项目的依赖中,并与其他必需的Hibernate库一起使用。开发人员需要熟悉JPA的基本概念和API,并且理解Hibernate特有的扩展和配置选项。 总的来说,hibernate-jpa-2.1-api 1.0.2提供了开发人员在使用JPA进行数据持久化时的基本工具和功能。它是Hibernate团队为了支持JPA 2.1规范而发布的一个版本,开发人员可以使用它来简化和灵活地操作数据库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值