sharp-database中的BaseDAOImpl使用指北

如何使用

BaseDAOImpl 的实现依赖于 SQLUtilsSharpService,主要是表的面向对象的CRUD操作。

让DAO继承 BaseDAOImpl。 实体对象继承BaseEntity

@SuperBuilder
@Getter
@Setter
@NoArgsConstructor
public class BaseEntity extends SimpleEntity {

    @Column(updatable = false)
    private Long createdBy;

    @Column(updatable = false)
    private Instant createdAt;

    private Long updatedBy;

    private Instant updatedAt;

    @Column(BaseEntityConstants.LOGIC_DELETE_COLUMN_NAME)
    private Boolean deleted;

}

`SimpleEntity.java`
```java
@SuperBuilder
@Getter
@Setter
@NoArgsConstructor
public class SimpleEntity {

    @Id
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        if (obj instanceof SimpleEntity) {
            SimpleEntity dataEntity = (SimpleEntity)obj ;
            if (dataEntity.id != null && dataEntity.id.equals(id))
                return true;
        }

        return false;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(id).toHashCode();
    }
}

手动指定表名和字段(字段的顺序要和entity属性的定义的顺序相同)

@Repository
public class ProjectDAO extends BaseDAOImpl<Project> {

    public ProjectDAO() {
        super("t_project", "id,title,description,cover_url,owner_id,created_by,created_at,updated_by,updated_at,is_deleted", "id");
    }
}

使用注解自动识别(推荐)

@Repository
public class ProjectGroupDAO extends BaseDAOImpl<ProjectGroup> {
}

ProjectGroup.java

@TableName("t_project_group")
@Getter
@Setter
public class ProjectGroup extends BaseEntity {

    private String title;

    private Long parentId;

    @ColumnName("group_id")
    private Long groupId;
}

如果没有注解 @ColumnName ,默认列名为驼峰名转下划线;没有注解 @TableName 默认表名为驼峰名转下划线。@Transient不参与持久化;@Id主键标识。

不指定范型

@Repository
public class MapDAO extends BaseDAOImpl {

    public MapDAO() {
        super("t_project", "id,title,description,cover_url,owner_id,created_by,created_at,updated_by,updated_at,is_deleted", "id");
    }
}

跟指定范型的区别 select 返回的对象由范型的实体变成了 Map 接收。insert update不能处理对象参数。 等价于下面的代码:

@Repository
public class MapDAO extends BaseDAOImpl<Map> {

    public MapDAO() {
        super("t_project", "id,title,description,cover_url,owner_id,created_by,created_at,updated_by,updated_at,is_deleted", "id");
    }
}

测试

添加数据insert

  • 添加数据(数组参数)
public void insert(Object[] params)
@Test
public void testInsert() {
    // id,title,description,created_by,created_at,updated_by,updated_at,is_deleted,cover_url,owner_id
    projectService.insert(new Object[]{
            null, "title-xxl", "description", 1, null, 1, null, null, "", 1
    });
}

id created_at updated_at is_deleted 会使用默认的 DefaultColumnAutoFill 填充。

DefaultColumnAutoFill.java

public class DefaultColumnAutoFill implements ColumnAutoFill {

    @Override
    public Map<String, Object> insertFill() {
        Map<String, Object> fillMap = Maps.newHashMapWithExpectedSize(4);
        LocalDateTime now = LocalDateTime.now();
        fillMap.put("id", IdGenerator.getSequenceId());
        fillMap.put("created_at", now);
        fillMap.put("updated_at", now);
        fillMap.put("is_deleted", false);
        return fillMap;
    }

    @Override
    public Map<String, Object> updateFill() {
        Map<String, Object> fillMap = Maps.newHashMapWithExpectedSize(2);
        LocalDateTime now = LocalDateTime.now();
        fillMap.put("updated_at", now);
        return fillMap;
    }
}

也可以自已定义使 created_by updated_by 也会被自动填充

@Bean
public ColumnAutoFill fill() {
    return new ColumnAutoFill() {
        @Override
        public Map<String, Object> insertFill() {
            Map<String, Object> fill = new DefaultColumnAutoFill().insertFill();
            fill.put("created_by", 0);
            fill.put("updated_by", 0);
            return fill;
        }

        @Override
        public Map<String, Object> updateFill() {
            Map<String, Object> fill = new DefaultColumnAutoFill().updateFill();
            fill.put("updated_by", 0);
            return fill;
        }
    };
}
  • 添加数据(对象参数)
    public int insert(T t) 
@Test
public void testInsert() {
    Project project = new Project();
    project.setTitle("save T");
    project.setDescription("dddd");
    projectDAO.insert(project);
    System.out.println(project.getId());
    Assert.assertNotNull(project.getId());
}
  • 批量添加数据
public void insert(List<?> paramsList)

数组参数

@Test
public void testInsertAll() {
    List<Object[]> paramsList = Lists.newArrayList(
            new Object[]{
                    IDUtils.genItemId(), "title-b", "description", 1, LocalDateTime.now(), 1, LocalDateTime.now(), 0, "", 1
            },
            new Object[]{
                    IDUtils.genItemId(), "title-c", "description", 1, LocalDateTime.now(), 1, LocalDateTime.now(), 0, "", 1
            });
    projectService.insert(paramsList);
}

对象参数

@Test
public void testInsert() {
    Project project1 = new Project();
    project1.setTitle("save TT1");
    project1.setDescription("dddd1");
    project1.setCoverUrl("http://baidu.com");

    Project project2 = new Project();
    project2.setTitle("save TT2");
    project2.setDescription("dddd2");

    List<Project> list = Lists.newArrayList(project1, project2);

    projectDAO.insert(list);
}

删除数据delete

  • 根据ID删除数据
public void deleteById(Serializable id)
@Test
public void testDeleteById() {
    projectService.deleteById(11L);
}
  • 根据ID批量删除数据
public void deleteByIds(String ids)
@Test
public void testDeleteByIds() {
    projectService.deleteByIds("1632391637675732, 1632391637678836");
}

修改数据update

  • 根据ID更新数组参数
public int update(Object[] params, Serializable id)
@Test
public void testUpdate() {
    projectService.update(new Object[]{
        "title-update", "description", 1, LocalDateTime.now(), 1, LocalDateTime.now(), 0, "", 1
    }, 1341320525040701442L);
}
  • 根据ID更新数据,指定更新列
public int update(String updateColumnNames, Object[] params, Serializable id)
@Test
public void testUpdate2() {
    int count = projectService.update("title", new Object[]{
            "title-update",
    }, 1341320525040701442L);

    Assert.assertEquals(1, count);
}
  • 根据ID更新对象参数
public int update(T t)
@Test
public void testUpdate() {
    ProjectGroup2 project = new ProjectGroup2();

    project.setId(473905081847549952L);
    project.setTitle("yes =>");
    project.setGroupId(0L);
    project.setParentId(11L);
    project.setDeleted(true);
    Assert.assertEquals(1, projectGroup2DAO.update(project));
}

查询数据select

  • 根据ID查找数据
public Optional<T> selectById(Serializable id)
@Test
public void testSelectById() {
    Optional<Project> optional = projectService.selectById(1341320525040701442L);
    Project project = optional.get();
    Assert.assertEquals("title-update", project.getTitle());

    Optional<Project> optional2 = projectService.selectById(-12);
    Assert.assertEquals(false, optional2.isPresent());
}
  • 根据ID批量查找数据
public List<T> selectByIds(String ids)
public List<T> selectByIds(Collection<?> ids)
@Test
public void testSelectByIds() {
    List<Project> list = projectService.selectByIds("1341320525040701442,1341368810614910978");
    Assert.assertEquals(2, list.size());

    List<Project> list2 = projectService.selectByIds(Arrays.asList(1341320525040701442L));
    Assert.assertEquals(1, list2.size());
}
  • 根据条件查找数据1
public List<T> selectByParams(Map<String, Object> params)
@Test
public void testParams() {
    Map<String, Object> params = Maps.newHashMapWithExpectedSize(2);
    params.put("title", "haha");
    params.put("description", "world");
    List<Project> list = projectService.selectByParams(params);
    Assert.assertEquals(1, list.size());
}
  • 根据条件查找数据2
/**
 * name=23&age=15,13 => name=:name AND age IN(:age)
 *
 * @param queryString
 * @return
 */
public List<T> selectByParams(String queryString)
@Test
public void testParams2() {
    List<Project> list = projectService.selectByParams("title=haha&created_by=156629745675451,156629745675452");
    Assert.assertEquals(4, list.size());
}
  • 根据条件查找数据3,自定义条件SQL
public List<T> selectByParams(String queryString, String conditionSQL)
@Test
public void testParams3() {
    List<Project> list = projectService.selectByParams("title=haha&created_by=156629745675452,156629745675454", "title=:title OR created_by IN(:created_by)");
    Assert.assertEquals(6, list.size());
}
  • 获取所有数据
public List<T> selectAll()
@Test
public void testSelectAll() {
    List<Project> list = projectService.selectAll();
    System.out.println(list.size());
}