资深Java开发工程师优秀代码案例学习探究分享

      哎呀,好久没有更新文章了,年后忙着学习、面试和跳槽,一直也没有进行更新文章,这周刚入职新公司,熟悉了一周项目代码,真是佩服资深Java开发工程师所写的代码啊,正好从明天开始是清明小长假,那我就趁着小长假来分享下优秀代码。为了不让自己懒惰,所以今天我就赶紧先写了个文章开头好让我接下来的几天里能够去付出实际行动。好了,废话少说,祝大家清明节快乐,俺下班喽,接下来几天俺要好好分享俺的代码案例哦;下班了下班了,溜了溜了,拜拜~~~
      1、如何省略写类中@Autowried注解:
            这个功能完成非常简单,只需要在类头添加注解@RequiredArgsConstructor即可,代码如下所示:

@RestController
@RequestMapping("/v1/api/sysArea")
//省略@Autowired注解的注解
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysAreaService {
	//自动注入SysAreaDomainService类,省略@Autowried注解
    private final SysAreaDomainService sysAreaDomainService;
	//自动注入SysAreaDomainService类,省略@Autowried注解
    private final SysAreaDTOConvert sysAreaDTOConvert;
    
    //下面写功能方法接口即可
    
}

      2、一个实体类属性复制到另一个实体类的属性中,其工具类如下图所示:

/**
*A实体复制到B实体中的工具类,source代表源实体,target代表目标实体
*在BeanUtils官方工具类上进行改进,增加其判断源实体与目标实体都不为null
**/
public class MyselfBeanUtil {
    public static void copyProperties(Object source, Object target) {
        if (null != source && null != target) {
            BeanUtils.copyProperties(source, target);
        }
    }
}

      方法中调用该工具类的实现代码如下所示:

	@PostMapping(value = "/findPage")
    public MultiResponse<SysAreaDTO> findPage(@RequestBody @Valid SysAreaQueryDTO param) {
        SysAreaQuery query = new SysAreaQuery();
        //调用MyselfBeanUtil工具类中复制方法
        MyselfBeanUtil.copyProperties(param, query);
        List<SysArea> sysAreaList = sysAreaDomainService.findPage(query);
        int total = sysAreaDomainService.findCount(query);
        List<SysAreaDTO> sysAreaDTOList = sysAreaDTOConvert.domainList2DTOList(sysAreaList);
        return MultiResponse.of(sysAreaDTOList, total);
    }

      3、实体判断是否为空的两种判断方式——null != bean 和 bean != null的区别:首先两者无论是在功能上还是运行处理效率上,两者是没有任何区别,但是在使用过程中我还是推荐使用第一种null != bean的写法,这种写法可以很好的给我们进行在代码编写过程中防止漏写 号,因为在null != bean的写法中,如果忘记写!则会进行报错,而在 bean != null的写法中则会不报错,而是将null赋值给bean实体,在后期中我们很难查错和改正。
      个人认为哈,当看到你写null != bean时,感觉你就是老司机一枚,由心的佩服大哥你真牛逼;但是当我看到你写bean != null时感觉“垃圾,菜鸟一枚,竟然还这样写”。
      4、通过equals判断两个Object是否相等:

String str = "";
if(str.equals("admin")){
	return ...;
}

如果采用上面这种方式进行判断的话,如果str为null的话,则会报空指针异常,因此我推荐大家使用if("admin".equals(str))这种写法,这种不会报空指针异常。
      5、判断list集合是否为空的listUtil工具类,代码如下所示:

/**
*判断list集合是否为null的工具类
*返回值为boolean类型
*/
public class ListUtil {

    public static <T> boolean isEmpty(List<T> list) {
        return null == list || list.size() == 0;
    }

    public static <T> boolean isNotEmpty(List<T> list) {
    	//这个是我最佩服的判断是否不为空,直接来个!isEmpty(list),真叼,不亏为大佬
        return !isEmpty(list);
    }

}

ListUtil工具类其用法:

//为null返回true;否则返回为false
ListUtil.isEmpty(list);

      6、lombok中的@EqualsAndHashCode()注解用法与其功能
            首先其用法如下所示:

@Data
@EqualsAndHashCode(callSuper = true)
public class SysAreaTreeQueryDTO extends PageQuery {
    /**
     * 角色ID
     */
    private Integer roleId;

    /**
     * 最大查询深度areaType 0-国家 1-省 2-市 3-区 默认查询到(2-市)
     */
    private Integer maxAreaType=2;
}

            注意:此注解只能当类中存在继承父类的时候才能使用,否则会进行报错,也就是类后面存在extends FuLei (继承父类)。
            功能:@Data注解是@Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode这个五个注解合集;且@EqualsAndHashCode注解中callSuper属性值默认为false,也就是当该类new出来多个对象时,多个对象比较时,他们类中继承父类属性值不进行Equals和HashCode进行比较,因此导致出现问题的可能性。
            简单来说就是当子类继承父类时,进行比较时,是否比较继承父类中的属性值,代码样例如下所示:
            第一种情况:不添加@EqualsAndHashCode(callSuper = true)注解:
在这里插入图片描述在这里插入图片描述在这里插入图片描述当看到输出结果为true,但是我们两个对象是明显不相等的,不相等的属性为继承父类的父类id,明显可以发现两个对象没有进行比较父类中属性值。
            第二种情况:添加@EqualsAndHashCode(callSuper = true)注解:
在这里插入图片描述在这里插入图片描述在这里插入图片描述通过输出结果为false,我们可以发现两个对象之间进行比较了继承父类中属性。
            好了,通过上面的例子,大家可以直观了解该注解功能,举例还是比长篇大论要简洁明了的多得多,好了,这个知识点就到此结束。
      7、mapper.xml文件中部分SQL语句重复使用方法实现。
            上周打开代码的mapper.xml文件中的SQL语句,当时直接震惊了,真叼啊,第一次发现SQL标签中的语句拼接和重复利用部分SQL语句,然后分析了下,在这里和大家分享下,代码示例如下图所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.focusmedia.fdo.tunnel.mapper.sys.SysCodeInfoQueryMapper">
    <resultMap id="BaseResultMap" type="cn.focusmedia.fdo.tunnel.dataobject.authority.SysCodeInfoDO">
        <!--
          WARNING - @mbg.generated
        -->
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="code_info_id" jdbcType="VARCHAR" property="codeInfoId"/>
        <result column="code_type_id" jdbcType="VARCHAR" property="codeTypeId"/>
        <result column="value" jdbcType="VARCHAR" property="value"/>
        <result column="content" jdbcType="VARCHAR" property="content"/>
        <result column="parent_value" jdbcType="VARCHAR" property="parentValue"/>
        <result column="sort_no" jdbcType="INTEGER" property="sortNo"/>
        <result column="valid_status" jdbcType="TINYINT" property="validStatus"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="create_user_id" jdbcType="VARCHAR" property="createUserId"/>
        <result column="create_user_name" jdbcType="VARCHAR" property="createUserName"/>
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
        <result column="update_user_id" jdbcType="VARCHAR" property="updateUserId"/>
        <result column="update_user_name" jdbcType="VARCHAR" property="updateUserName"/>
        <result column="is_delete" jdbcType="TINYINT" property="isDelete"/>
        <result column="data_version" jdbcType="INTEGER" property="dataVersion"/>
        <result column="remark" jdbcType="LONGVARCHAR" property="remark"/>
    </resultMap>
    <sql id="ALL_COLUMNS">
        id
        ,
		code_info_id,
		code_type_id,
		value,
		content,
		parent_value,
		sort_no,
		valid_status,
		remark,
		create_time,
		create_user_id,
		create_user_name,
		update_time,
		update_user_id,
		update_user_name,
		is_delete,
		data_version
    </sql>

    <sql id="COMMON_SELECT">
        SELECT
        <include refid="ALL_COLUMNS"/>
        FROM tr_sys_code_info
    </sql>

    <sql id="COMMON_WHERE">
        <where>
            <if test="query.id != null">
                and id = #{query.id,jdbcType=BIGINT}
            </if>
            <if test="query.codeInfoId != null">
                and code_info_id = #{query.codeInfoId,jdbcType=VARCHAR}
            </if>
            <if test="query.codeTypeId != null">
                and code_type_id = #{query.codeTypeId,jdbcType=VARCHAR}
            </if>
            <if test="query.codeTypeIdList != null and query.codeTypeIdList.size() > 0">
                and code_type_id in
                <foreach collection="query.codeTypeIdList" open="(" separator="," close=")" item="codeTypeId" index="codeTypeId">
                    #{codeTypeId}
                </foreach>
            </if>
            <if test="query.value != null">
                and value = #{query.value,jdbcType=VARCHAR}
            </if>
            <if test="query.content != null">
                and content = #{query.content,jdbcType=VARCHAR}
            </if>
            <if test="query.parentValue != null">
                and parent_value  LIKE CONCAT('%|',#{query.parentValue},'|%')
            </if>
            <if test="query.sortNo != null">
                and sort_no = #{query.sortNo,jdbcType=INTEGER}
            </if>
            <if test="query.validStatus != null">
                and valid_status = #{query.validStatus,jdbcType=TINYINT}
            </if>
            <if test="query.createTime != null">
                and create_time = #{query.createTime,jdbcType=TIMESTAMP}
            </if>
            <if test="query.createUserId != null">
                and create_user_id = #{query.createUserId,jdbcType=VARCHAR}
            </if>
            <if test="query.createUserName != null">
                and create_user_name = #{query.createUserName,jdbcType=VARCHAR}
            </if>
            <if test="query.updateTime != null">
                and update_time = #{query.updateTime,jdbcType=TIMESTAMP}
            </if>
            <if test="query.updateUserId != null">
                and update_user_id = #{query.updateUserId,jdbcType=VARCHAR}
            </if>
            <if test="query.updateUserName != null">
                and update_user_name = #{query.updateUserName,jdbcType=VARCHAR}
            </if>
            <if test="query.isDelete != null">
                and is_delete = #{query.isDelete,jdbcType=TINYINT}
            </if>
            <if test="query.dataVersion != null">
                and data_version = #{query.dataVersion,jdbcType=INTEGER}
            </if>
            <if test="query.remark != null">
                and remark = #{query.remark,jdbcType=LONGVARCHAR}
            </if>
        </where>
    </sql>

    <select id="page" parameterType="map" resultMap="BaseResultMap">
        <include refid="COMMON_SELECT"/>
        <include refid="COMMON_WHERE"/>
        <if test="limit>0">
        limit #{offset}, #{limit}
        </if>
    </select>

    <select id="count" parameterType="map" resultType="java.lang.Integer">
        select
        count(1)
        FROM tr_sys_code_info
        <include refid="COMMON_WHERE"/>
    </select>
</mapper>

        上面例子举得稍微长了些,但是大家分析起来很简单,这里我给大家简单分析下:
1、sql标签:这里表明这标签内部的内容为sql语句,id为唯一标识符,在引用时可以直接写id名称即可。
2、sql标签内部where标签:where标签就是和SQL语句的where条件语句是一样的作用。
3、sql标签内部if标签:if标签就是和java的if判断作用是一样的。
4、select标签中include标签:起到引用SQL标签内容,其中refid属性值是引用SQL的id,简而言之就是将SQL标签内语句引入该标签内部。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岭岭颖颖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值