JPA 使用

批量操作

 @PersistenceContext
 private EntityManager em;

 @Transactional
    public void batchUpateCustom(List<User> users) {
        // TODO Auto-generated method stub
        for(int i = 0; i < users.size(); i++) {  
            em.merge(users.get(i));  
            if(i % 30== 0) {  
                em.flush();  
                em.clear();  
            }  
        }
    }

保存或更新

        User user = new User();
        user.setId(99);
        user.setAddress("上海");
        user.setName("张三");
        user.setPhone("110");

        //保存单个
        userRepository.save(user);
        //保存或更新
        userRepository.saveAndFlush(user);
    

解析方法名创建查询

规则:
find+全局修饰+By+实体的属性名称+限定词+连接词+ ...(其它实体属性)+OrderBy+排序属性+排序方向

全局修饰: Distinct, Top, First
关键词: IsNull, IsNotNull, Like, NotLike, Containing, In, NotIn,
IgnoreCase, Between, Equals, LessThan, GreaterThan, After, Before...
排序方向: Asc, Desc
连接词: And, Or

And --- 等价于 SQL 中的 and 关键字,比如 findByUsernameAndPassword(String user, Striang pwd);
Or --- 等价于 SQL 中的 or 关键字,比如 findByUsernameOrAddress(String user, String addr);
Between --- 等价于 SQL 中的 between 关键字,比如 findBySalaryBetween(int max, int min);
LessThan --- 等价于 SQL 中的 "<",比如 findBySalaryLessThan(int max);
GreaterThan --- 等价于 SQL 中的">",比如 findBySalaryGreaterThan(int min);
IsNull --- 等价于 SQL 中的 "is null",比如 findByUsernameIsNull();
IsNotNull --- 等价于 SQL 中的 "is not null",比如 findByUsernameIsNotNull();
NotNull --- 与 IsNotNull 等价;
Like --- 等价于 SQL 中的 "like",比如 findByUsernameLike(String user);
NotLike --- 等价于 SQL 中的 "not like",比如 findByUsernameNotLike(String user);
OrderBy --- 等价于 SQL 中的 "order by",比如 findByUsernameOrderBySalaryAsc(String user);
Not --- 等价于 SQL 中的 "! =",比如 findByUsernameNot(String user);
In --- 等价于 SQL 中的 "in",比如 findByUsernameIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
NotIn --- 等价于 SQL 中的 "not in",比如 findByUsernameNotIn(Collection<String> userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;

JPQL查询

// JPQL查询
@Query("select a from user a where a.id = ?1") 
 public User findById(Long id);

// 修改
@Modifying 
 @Query("update User a set a.name = ?1 where a.id < ?2") 
 public int updateName(String name, Long id);

// 分页
 @Query("select u from User u where u.name=?1")
    public List<User> findByName(String name, Pageable pageable);

//使用原生sql,只需要@Query(nativeQuery=true)标识即可.

判断是否存在

       //根据主键判断是否存在
        userRepository.exists(1);

        User user = new User();
        user.setName("小红");
        //根据条件判断是否存在
        userRepository.exists(Example.of(user));

双向关联 mappedBy

hibernate会根据实体类属性的变化执行相应的SQL,如果设置了双向的关联关系,那么在更新实体类之间的关系时,需要同时更新两端的关系,这样,会执行两条SQL,但实际上,从数据库的角度看,只需要执行一条SQL。

这时,就需要设置mappedBy属性,表明哪一端为关系的控制端,hibernate只根据关系的控制端的变化而执行相应的SQL。

Casecade 级联操作

orphanRemoval 和 CascadeType.REMOVE的区别

 https://stackoverflow.com/questions/4329577/jpa-2-0-orphanremoval-true-vs-on-delete-cascade

An example taken form here:

When an Employee entity object is removed, the remove operation is cascaded to the referenced Address entity object. In this regard, orphanRemoval=true and cascade=CascadeType.REMOVE are identical, and if orphanRemoval=true is specified, CascadeType.REMOVE is redundant.

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g. Address) that should not exist without a reference from an owner object (e.g. Employee).

  • If only cascade=CascadeType.REMOVE is specified, no automatic action is taken since disconnecting a relationship is not a remove operation.

To avoid dangling references as a result of orphan removal, this feature should only be enabled for fields that hold private non shared dependent objects.

参考

SpringDataJPA学习记录(二)--增删改查

原文地址:https://www.cnblogs.com/tonyq/p/7881476.html