MyBatis实现动态SQL更新业务用户的查询服务

创建业务用户

区别于身份管理模块(Identity模块)的鉴权用户IdentityUser,业务用户(BusinessUser)是围绕业务系统中“用户”这一定义的领域模型。如:在一个医院系统中,业务用户可以是医生、护士、患者;在一个OA系统中,业务用户可以是员工、管理员、客户等。

业务用户和鉴权用户由同步机制关联,业务用户通过分布式事件(DistributedEvent)的同步器(Synchronizer)与鉴权用户关联同步。

在Health业务模块中,定义两种业务用户:

Client: 客户;

Employee: 员工。

这些业务用户继承自HealthUser,HealthUser是业务用户的基类,包含了业务用户的基本信息,如姓名,性别,出生日期,身份证号等。并且需要实现IUpdateUserData接口,以便在同步鉴权用户信息时,更新业务用户的基本信息。

Employee包含工号,职称,简介等信息。其领域模型定义如下:

public class Employee : HealthUser<Guid>, IUser, IUpdateUserData
{
    [StringLength(12)]
    public string EmployeeNumber { get; set; }

    [StringLength(64)]
    public string EmployeeTitle { get; set; }

    public string Introduction { get; set; }

    ...
}

Client包含客户号,身高,体重,婚姻状况等信息。其领域模型定义如下:

public class Client : HealthUser<Guid>, IUser, IUpdateUserData
{

    //unique

    [StringLength(12)]
    public string ClientNumber { get; set; }

    public string ClientNumberType { get; set; }

    [Range(0.0, 250.0)]
    public double? Height { get; set; }


    [Range(0.0, 1000.0)]
    public double? Weight { get; set; }

    public string Marriage { get; set; }

    public string Status { get; set; }
}

创建业务用户同步器

以Client为例,ClientLookupService是业务用户的查询服务,其基类UserLookupService定义了关联用户的查询接口,包括按ID查询,按用户名查询,按组织架构查询,按户关系查询等。

创建ClientLookupService, 代码如下

public class ClientLookupService : UserLookupService<Client, IClientRepository>, IClientLookupService
{
    public ClientLookupService(
        IClientRepository userRepository,
        IUnitOfWorkManager unitOfWorkManager)
        : base(
            userRepository,
            unitOfWorkManager)
    {

    }

    protected override Client CreateUser(IUserData externalUser)
    {
        return new Client(externalUser);
    }
}

同步器订阅了分布式事件EntityUpdatedEto,当鉴权用户更新时,同步器将更新业务用户的基本信息。

创建ClientSynchronizer,代码如下

public class ClientSynchronizer :
        IDistributedEventHandler<EntityUpdatedEto<UserEto>>,
    ITransientDependency
{
    protected IClientRepository UserRepository { get; }
    protected IClientLookupService UserLookupService { get; }

    public ClientSynchronizer(
        IClientRepository userRepository,
        IClientLookupService userLookupService)
    {
        UserRepository = userRepository;
        UserLookupService = userLookupService;
    }

    public async Task HandleEventAsync(EntityUpdatedEto<UserEto> eventData)
    {
        var user = await UserRepository.FindAsync(eventData.Entity.Id);
        if (user != null)
        {
            if (user.Update(eventData.Entity))
            {
                await UserRepository.UpdateAsync(user);
            }
        }
    }
}

创建业务用户应用服务

以Employee为例

在应用层中创建EmployeeAppService,在这里我们实现对业务用户的增删改查操作。

EmployeeAppService继承自CrudAppService,它是ABP框架提供的增删改查的基类,其基类定义了增删改查的接口,包括GetAsync,GetListAsync,CreateAsync,UpdateAsync,DeleteAsync等。

OrganizationUnit为业务用户的查询接口的按组织架构查询提供查询依据。OrganizationUnitAppService注入到EmployeeAppService中。

public class EmployeeAppService : CrudAppService<Employee, EmployeeDto, Guid, GetAllEmployeeInput, CreateEmployeeInput>, IEmployeeAppService
{
    private readonly IOrganizationUnitAppService organizationUnitAppService;

}

创建CreateWithUserAsync方法,用于创建业务用户。

public async Task<EmployeeDto> CreateWithUserAsync(CreateEmployeeWithUserInput input)
{

    var createdUser = await identityUserAppService.CreateAsync(input);
    await CurrentUnitOfWork.SaveChangesAsync();
    var currentEmployee = await userLookupService.FindByIdAsync(createdUser.Id);
    ObjectMapper.Map(input, currentEmployee);
    var updatedEmployee = await Repository.UpdateAsync(currentEmployee);
    var result = ObjectMapper.Map<Employee, EmployeeDto>(updatedEmployee);

    if (input.OrganizationUnitId.HasValue)
    {
        await organizationUnitAppService.AddToOrganizationUnitAsync(
            new UserToOrganizationUnitInput()
            { UserId = createdUser.Id, OrganizationUnitId = input.OrganizationUnitId.Value });
    }
    return result;
}

删除接口由CrudAppService提供默认实现,无需重写。

创建UpdateWithUserAsync方法,用于更新业务用户。

public async Task<EmployeeDto> UpdateWithUserAsync(CreateEmployeeInput input)
{

    var currentEmployee = await userLookupService.FindByIdAsync(input.Id);
    if (currentEmployee == null)
    {
        throw new UserFriendlyException("没有找到对应的用户");
    }
    ObjectMapper.Map(input, currentEmployee);
    var updatedEmployee = await Repository.UpdateAsync(currentEmployee);
    var result = ObjectMapper.Map<Employee, EmployeeDto>(updatedEmployee);

    return result;
}

查询单个实体接口由CrudAppService提供默认实现,无需重写。

查询集合:

以Employee为例,查询接口所需要的入参为:

OrganizationUnitId:按组织架构查询用户
IsWithoutOrganization:查询不属于任何组织架构的用户
EmployeeTitle:按职称查询用户

创建GetAllEmployeeInput,代码如下

public class GetAllEmployeeInput : PagedAndSortedResultRequestDto
{
    public string EmployeeTitle { get; set; }

    public Guid? OrganizationUnitId { get; set; }
    public bool IsWithoutOrganization { get; set; }

}

重写CreateFilteredQueryAsync


protected override async Task<IQueryable<Employee>> CreateFilteredQueryAsync(GetAllEmployeeInput input)
{
    var query = await ReadOnlyRepository.GetQueryableAsync().ConfigureAwait(continueOnCapturedContext: false);

    if (input.OrganizationUnitId.HasValue && !input.IsWithoutOrganization)
    {
        var organizationUnitUsers = await organizationUnitAppService.GetOrganizationUnitUsersAsync(new GetOrganizationUnitUsersInput()
        {
            Id = input.OrganizationUnitId.Value
        });
        if (organizationUnitUsers.Count() > 0)
        {
            var ids = organizationUnitUsers.Select(c => c.Id);
            query = query.Where(t => ids.Contains(t.Id));
        }
        else
        {
            query = query.Where(c => false);
        }
    }
    else if (input.IsWithoutOrganization)
    {
        var organizationUnitUsers = await organizationUnitAppService.GetUsersWithoutOrganizationAsync(new GetUserWithoutOrganizationInput());
        if (organizationUnitUsers.Count() > 0)
        {
            var ids = organizationUnitUsers.Select(c => c.Id);
            query = query.Where(t => ids.Contains(t.Id));
        }
        else
        {
            query = query.Where(c => false);
        }
    }
    query = query.WhereIf(!string.IsNullOrEmpty(input.EmployeeTitle), c => c.EmployeeTitle == input.EmployeeTitle);
    return query;
}

至此,我们已完成了对业务用户的增删改查功能实现。

创建控制器

在HttpApi项目中创建EmployeeController,代码如下:

[Area(HealthRemoteServiceConsts.ModuleName)]
[RemoteService(Name = HealthRemoteServiceConsts.RemoteServiceName)]
[Route("api/Health/employee")]
public class EmployeeController : AbpControllerBase, IEmployeeAppService
{
    private readonly IEmployeeAppService _employeeAppService;

    public EmployeeController(IEmployeeAppService employeeAppService)
    {
        _employeeAppService = employeeAppService;
    }

    [HttpPost]
    [Route("CreateWithUser")]

    public Task<EmployeeDto> CreateWithUserAsync(CreateEmployeeWithUserInput input)
    {
        return _employeeAppService.CreateWithUserAsync(input);
    }

    [HttpDelete]
    [Route("Delete")]
    public Task DeleteAsync(Guid id)
    {
        return _employeeAppService.DeleteAsync(id);
    }

    [HttpPut]
    [Route("UpdateWithUser")]

    public Task<EmployeeDto> UpdateWithUserAsync(CreateEmployeeInput input)
    {
        return _employeeAppService.UpdateWithUserAsync(input);
    }

    [HttpGet]
    [Route("Get")]
    public Task<EmployeeDto> GetAsync(Guid id)
    {
        return _employeeAppService.GetAsync(id);
    }

    [HttpGet]
    [Route("GetAll")]
    public Task<PagedResultDto<EmployeeDto>> GetAllAsync(GetAllEmployeeInput input)
    {
        return _employeeAppService.GetAllAsync(input);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Mybatis-Plus是Mybatis的一个增强工具,它可以优化我们的开发效率。在实际的项目开发中,我们通常需要编写复杂的SQL查询语句来满足业务需求。下面我将介绍如何在自定义的Mapper类中实现复杂的SQL查询操作。 Mybatis-Plus提供了很多基础的查询方法,比如新增、修改、删除、查询全部等,但是当我们遇到一些比较复杂的查询需求时,需要自己手动编写SQL语句。我们可以在自定义的Mapper接口中定义SQL查询方法,然后在XML文件中编写SQL语句,最后通过Mybatis-Plus的注解进行映射。 首先,在自定义的Mapper接口中定义一个查询方法,比如:selectUserList。在这个方法上使用注解@Select,用于映射XML文件中的SQL语句。在这个方法的参数中,我们可以传入一些查询条件用于过滤查询结果,比如用户姓名、年龄等信息。如果需要分页查询,我们可以传入Page对象,然后在XML文件中使用<if>标签判断是否需要拼装分页的SQL语句。 然后,在XML文件中编写SQL语句。针对不同的查询需求,我们可以使用各种关键字、函数、运算符等语法进行拼装。在使用变量的时候,需要使用#{XXX}形式的占位符来代替变量,同时也可以使用${XXX}形式的占位符来代替SQL关键字、表名等信息。 最后,在Mapper接口上使用@Mapper注解将这个接口进行映射,然后在Service层中调用这个接口中定义的查询方法即可。如果需要进行分页查询,我们需要手动创建一个Page对象,并设置分页信息,然后将这个对象传入到Mapper接口中即可。 总之,对于比较复杂的SQL查询操作,我们可以通过自定义Mapper接口、XML文件以及Mybatis-Plus注解的方式来实现。这样可以大大提升我们的查询效率和开发效率,减少我们的工作量和出错的概率。 ### 回答2: MyBatis-Plus 是一个 Mybatis 的增强工具,在持久层操作方面做了很多增强和优化,其中包括自定义复杂 SQL 查询实现自定义复杂 SQL 查询的步骤如下: 1. 在实体类中添加查询参数的字段,如下: ``` public class User { private Integer id; private String name; private Integer age; private String phone; // getter and setter ... } ``` 2. 在 mapper.xml 中编写自定义复杂 SQL 查询语句: ``` <select id="selectByCustomQuery" resultMap="BaseResultMap"> SELECT id,name,age,phone FROM user <where> <if test="name!=null"> and name like concat('%', #{name}, '%') </if> <if test="age!=null"> and age = #{age} </if> <if test="phone!=null"> and phone like concat('%', #{phone}, '%') </if> </where> </select> ``` 3. 在 mapper 接口中添加自定义查询的方法: ``` public interface UserMapper extends BaseMapper<User> { List<User> selectByCustomQuery(@Param("name") String name, @Param("age") Integer age, @Param("phone") String phone); } ``` 4. 在 service 层中调用自定义查询的方法: ``` @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> findByCustomQuery(String name, Integer age, String phone) { return userMapper.selectByCustomQuery(name, age, phone); } } ``` 最后,调用 findByCustomQuery 方法可以实现自定义复杂 SQL 查询。 以上是实现自定义复杂 SQL 查询的简单步骤,需要注意的是在 XML 中编写 SQL 语句时,需要加入防 SQL 注入的措施。 ### 回答3: MyBatis-Plus是一款基于MyBatis的增强工具包,它封装了很多MyBatis的常用操作,例如:分页查询、自动逆向工程、注解CRUD、性能分析等,其中自定义复杂SQL查询也得到了很好的支持。 MyBatis-Plus自定义复杂SQL语句的步骤如下: 1.定义Mapper接口 在Mapper接口中定义自定义查询方法,例如: ```java @Select("SELECT * FROM user WHERE age > #{age}") List<User> selectByAge(Integer age); ``` 2.使用MyBatis-Plus提供的BaseMapper 在Mapper接口中继承MyBatis-Plus提供的BaseMapper,并使用@Mapper注解标记接口。 ```java @Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> selectByAge(Integer age); } ``` 3.使用XML方式实现自定义查询 如果自定义查询语句比较复杂,可以使用XML方式实现。在Mapper接口中定义方法,例如: ```java List<UserVO> selectUserVO(); ``` 在resources/mapper/UserMapper.xml中实现自定义sql语句,例如: ```xml <select id="selectUserVO" resultMap="userVOResultMap"> SELECT u.*, d.name AS deptName FROM user u LEFT JOIN department d ON u.dept_id = d.id </select> ``` 4.在Service层调用Mapper接口中的自定义方法 在Service层中注入Mapper,并调用Mapper接口中的自定义方法,例如: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<UserVO> selectUserVO() { return userMapper.selectUserVO(); } } ``` 以上就是使用MyBatis-Plus实现自定义复杂SQL查询的步骤,它可以很好地帮助我们提高数据查询的效率和灵活性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值