单表多租户的select/update/delete实现--@filter

@FilterDef(name="bookFilter",parameters={@ParamDef(name="perchase_cell_id",type="long")})
@Filter(name="bookFilter",condition="perchase_cell_id = :perchase_cell_id")
@Setter
@Getter
@MappedSuperclass
public class BaseEntity {
    @Column(name = "perchase_cell_id")
    public Long perchase_cell_id;
}
@Setter
@Getter
@NoArgsConstructor
@Entity
@Table(name = "item")
@ToString
public class ItemDto extends BaseEntity {

...

}
    public ItemDto getById(Long id){
       entityManager.unwrap(org.hibernate.Session.class).enableFilter("bookFilter").setParameter("perchase_cell_id", 1317l);
      
        String hql = "select i from ItemDto i where id = :id";
        ItemDto itemDto;
        try {
            itemDto = entityManager.createQuery(hql, ItemDto.class).setParameter("id", id).getSingleResult();
        }catch (NoResultException e){
            e.printStackTrace();
            return null;
        }
        return itemDto;
    }

 

1. @where和@filter的区别: 前者的注解不能被继承, 不能设置变参

2.find()方法查询无效, @filter只对hql有效

3.如果只是对有需求的dao层作的entitymanager设置filter, 则关联查询不会使用filter, 如下, 第一个主查寻的true_name做过滤有效,第二个是关联查询, true_name过滤无效

 

  @Transactional
    public UserDto getByPhone(String phone){
        entityManager.unwrap(Session.class).enableFilter("bookFilter").setParameter("true_name", "李阳");
        String hql = "select u from UserDto u where phone = :phone";
        List userDtos = entityManager.createQuery(hql, UserDto.class).setParameter("phone", phone).getResultList();
        if(userDtos.size()==1)
            return userDtos.get(0);
        return null;
    }
Hibernate: 
    select
        userdto0_.id as id1_34_,
        userdto0_.true_name as true_nam2_34_,
        userdto0_.login_auth as login_au3_34_,
        userdto0_.password as password4_34_,
        userdto0_.phone as phone5_34_,
        userdto0_.position_id as position6_34_,
        userdto0_.user_type as user_typ7_34_ 
    from
        user userdto0_ 
    where
        userdto0_.true_name = ? 
        and userdto0_.phone=?
Hibernate: 
    select
        employees0_.user_id as user_id6_19_1_,
        employees0_.id as id1_19_1_,
        employees0_.id as id1_19_0_,
        employees0_.true_name as true_nam2_19_0_,
        employees0_.deleted as deleted3_19_0_,
        employees0_.position_id as position4_19_0_,
        employees0_.status as status5_19_0_,
        employees0_.user_id as user_id6_19_0_,
        employees0_.warehouse_id as warehous7_19_0_ 
    from
        manager_employee employees0_ 
    where
        employees0_.user_id=?

 

你可能感兴趣的:(hibernate)