MyBatis【四】注解开发及 Lombok

八、使用注解开发

8.1 面向接口编程

  • 大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程
  • 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的实现 , 大家都遵守共同的标准 , 使得开发变得容易 , 规范性更好
  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。

  • 接口的本身反映了系统设计人员对系统的抽象理解。

  • 接口应有两类:

    • 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);

    • 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);

  • 一个体有可能有多个抽象面。抽象体与抽象面是有区别的。

三个面向区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构

8.2 使用注解开发

mybatis最初配置信息是基于 XML,映射语句(SQL)也是定义在 XML 中的。而到 MyBatis 3 提供了新的基于注解的配置。不幸的是,Java 注解的的表达力和灵活性十分有限。最强大的 MyBatis 映射并不能用注解来构建。

注意:使用注解开发,不需要 mapper.xml 映射文件

  1. 注解在接口上实现
public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}
  1. 需要在 MyBatis 核心配置文件中绑定接口(注入)
<!--绑定接口-->
<mappers>
    <mapper class="com.song.dao.UserMapper"/>
</mappers>
  1. 测试及 Debug
@Test
public void getUsers(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    // 底层主要应用反射
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    List<User> users = mapper.getUsers();
    for (User u: users){
        System.out.println(u);
    }
    sqlSession.close();
}

image-20200617112348564

本质:反射机制实现

底层:动态代理

8.3 注解 CRUD(@select ()、@update ()、@Insert ()、@delete ())

增删改一定记得对事务的处理,可以在工具类 MybatisUtils.class 创建的时候实现自动提交事务

实现方式:改造MybatisUtils工具类的 getSession( ) 方法,重载实现。

public class MybatisUtils {
    ...
    public static SqlSession getSqlSession(){
        // 打开自动提交
        return sqlSessionFactory.openSession(true);
    }
}
  1. 必须先将接口注册绑定(通过class)到 MyBatis 的核心配置文件中(如果有多个接口,每个接口都要绑定)
<!--绑定接口-->
<mappers>
    <mapper class="com.song.dao.UserMapper"/>
</mappers>
  1. 编写接口,增加注解
public interface UserMapper {

    @Select("select * from user")
    List<User> getUsers();

    // 方法存在多个参数,所有参数前面必须加上 @Param("id") 注解,sql语句中#{}内的值要与这个值一致
    @Select("select * from user where id = #{id} ")
    User getUserById(@Param("id") int id);

    @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
    int addUser(User user);

    @Update("update user set name = #{name}, pwd = #{password} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id); // 注意 uid 
}
  1. 测试类测试

【注意】确保实体类和数据库字段对应

关于 @Param 注解

用于给方法参数起一个名字

  • 参数是基本类型或 String 类型,需要加上
  • 参数是引用类型 Javabean,不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议加上
  • 在 SQL 中引用的就是这里的 @Param(" ") 中设定的属性
  • 不使用 @Param 注解时,参数只能有一个,并且是 Javabean。

#{} 和 ${} 区别

  • #{} 的作用主要是替换预编译语句 (PrepareStatement) 中的占位符 ? 【推荐使用】

    安全,可以防止 SQL 注入

    INSERT INTO user (name) VALUES (#{name});
    INSERT INTO user (name) VALUES (?);
    
  • ${} 的作用是直接进行字符串替换

    INSERT INTO user (name) VALUES ('${name}');
    INSERT INTO user (name) VALUES ('kuangshen');
    

九、Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

使用步骤:

  1. 在 IDEA 中安装 Lombok
  2. 在项目中导入 Lombok 的 jar 包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
    <scope>provided</scope>
</dependency>
  1. 在实体类上加注解即可
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;    
}

常见注解:

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val

说明:

  • @Data:无参构造、get、set、tostring、hashcode、equals

  • @AllArgsConstructor:有参构造

  • @NoArgsConstructor:无参构造

原文地址:https://www.cnblogs.com/Songzw/p/13159471.html