Spring data jpa

1. Spring data jpa怎么去判断一个对象的是否为新对象呢?

 spring  data 提供了三种策略:

able 2.2. Options for detection whether an entity is new in Spring Data JPA

Id-Property inspection (default) By default Spring Data JPA inspects the Id-Property of the given Entity. If the Id-Property is null, then the entity will be assumed as new, otherwise as not new.
ImplementingPersistable If an entity implements the Persistable interface, Spring Data JPA will delegate the new-detection to the isNew - Method of the Entity. See theJavaDoc for details.
ImplementingEntityInformation One can customize the EntityInformation abstraction used in the SimpleJpaRepository implementation by creating a subclass ofJpaRepositoryFactory and overriding the getEntityInformation-Method accordingly. One then has to register the custom implementation ofJpaRepositoryFactory as a Spring bean. Note that this should be rarely necessary. See the JavaDoc for details.

 可以看出默认是判断是否有id。然后也可以采取其他策略,比如实现Persistable接口,然后重写isNew方法。

2. Spring data注解

3. Spring 方法查询策略

1. 使用 @Query 创建查询;
  @Query("select u from User u where u.userName=?1 ") 
  public List<User> findByQuery(String userName); 
2. JPA 命名查询语句创建查询 首先创建命名查询,如下
  @Entity
  @NamedQuery(name="User.findName",query="select u from User u where u.userName=?")   public class User implements Serializable { }

一共分为三种:


create : 直接通过解析方法名来创建查询语句,方法名的前缀可以是findBy, readBy, getBy

create-if-not-found(默认): 首先查看是否有@Query指定的语句,若没有则查看是否定义了符合条件的命名查询,如果没有才执行create.

use-declared-query: 和create-if-not-found不同的是,如果前两种都没有找到不create,而是抛出异常。

4. 使用 @Query 创建查询,除了使用annotation方式,还可以使用配置文件,在META-INF下创建一个$store-named-queries.properties

其中的key约定为$domainType.$methodName

The queries can even be externalized into a properties file—$store-named-queries.
properties, located in META-INF—where $store is a placeholder for jpa, mongo,
neo4j, etc. The key has to follow the convention of $domainType.$methodName. Thus, to
back our existing method with a externalized named query, the key would have to be
Customer.findByEmailAddress. The @Query annotation is not needed if named queries
are used.

5. @NoRepositoryBean

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
Iterable<T> findAll(Pageable sort);
<S extends T> S save(S entity);
<S extends T> S save(Iterable<S> entities);
}

Note that we additionally annotated the interface with @NoRepositoryBean to make sure
the Spring Data repository infrastructure doesn’t actually try to create a bean instance
for it。

添加了NoRepositoryBean注解,则spring不会为该接口创建一个实例。

原文地址:https://www.cnblogs.com/ranger2016/p/3932469.html