Java 面试系列:对数据库的基本操作步骤 + 面试题

2021-01-07  本文已影响0人  you的日常

MyBatis 最初的设计是基于 XML 配置文件的,但随着 Java 的发展(Java 1.5 开始引入注解)和 MyBatis 自身的迭代升级,终于在 MyBatis 3 之后就开始支持基于注解的开发了。

下面我们使用 Spring Boot + MyBatis 注解的方式,来实现对数据库的基本操作,具体实现步骤如下。

MyBatis 注解版

1)创建数据表

drop table if exists `t_user`;
create table `t_user` (
  `id` bigint(20) not null auto_increment comment '主键id',
  `username` varchar(32) default null comment '用户名',
  `password` varchar(32) default null comment '密码',
  `nick_name` varchar(32) default null,
  primary key (`id`)
) 
engine=innodb auto_increment=1 default charset=utf8;

2)添加依赖

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

3)增加配置文件

在 application.yml 文件中添加以下内容:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/learndb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  type-aliases-package: com.interview.model

4)创建实体类

public class UserEntity implements Serializable {
    private static final long serialVersionUID = -5980266333958177105L;
    private Integer id;
    private String userName;
    private String passWord;
    private String nickName;
    public UserEntity(String userName, String passWord, String nickName) {
        this.userName = userName;
        this.passWord = passWord;
        this.nickName = nickName;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
}

5)增加 Mapper 文件

public interface UserMapper {
    @Select("select * from t_user")
    @Results({
            @Result(property = "nickName", column = "nick_name")
    })
    List<UserEntity> getAll();

    @Select("select * from t_user where id = #{id}")
    @Results({
            @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Insert("insert into t_user(username,password,nick_name) values(#{userName}, #{passWord}, #{nickName})")
    void insert(UserEntity user);

    @Update("update t_user set username=#{userName},nick_name=#{nickName} where id =#{id}")
    void update(UserEntity user);

    @Update({"<script> ",
            "update t_user ",
            "<set>",
            " <if test='userName != null'>userName=#{userName},</if>",
            " <if test='nickName != null'>nick_name=#{nickName},</if>",
            " </set> ",
            "where id=#{id} ",
            "</script>"})
    void updateUserEntity(UserEntity user);

    @Delete("delete from t_user where id =#{id}")
    void delete(Long id);
}

使用 @Select@Insert@Update@Delete@Results@Result 等注解来替代 XML 配置文件。

6)添加 Mapper 包扫描

在启动类中添加@MapperScan,设置 Spring Boot 启动的时候会自动加载包路径下的 Mapper

@SpringBootApplication
@MapperScan("com.interview.mapper")
public class MybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
    }
}

7)编写测试代码

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testInsert() {
        userMapper.insert(new UserEntity("laowang", "123456", "老王"));
        Assert.assertEquals(1, userMapper.getAll().size());
    }
}

相关面试题

1.MyBatis 有哪些优缺点?

答:MyBatis 优缺点如下:

优点:

缺点:

上一篇下一篇

猜你喜欢

热点阅读