2022-04-05_数据库访问

2022-04-04  本文已影响0人  微笑碧落

0.前言

1.依赖

<!--导入JDBC的场景启动器-->
<!-- 包含HikariCP数据源-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

<!--导入数据库驱动,不同数据库,驱动器不一样-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!--引入 mybatis-spring-boot-starter 的依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

2.数据库配置

#数据源连接信息
#(application.yml)
# 注意如下的schemasName
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/schemasName
    driver-class-name: com.mysql.cj.jdbc.Driver

3.创建Mapper接口(注解方式)

@Select("select * from user where user_name = #{userName,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}")
    List<User> getByUserNameAndPassword(User user);
    @Delete("delete from user where id = #{id,jdbcType=INTEGER}")
    int deleteByPrimaryKey(Integer id);
    @Insert("insert into user ( user_id, user_name, password, email)" +
            "values ( #{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR})")
    int insert(User record);
    @Update(" update user" +
            "    set user_id = #{userId,jdbcType=VARCHAR},\n" +
            "      user_name = #{userName,jdbcType=VARCHAR},\n" +
            "      password = #{password,jdbcType=VARCHAR},\n" +
            "      email = #{email,jdbcType=VARCHAR}\n" +
            "    where id = #{id,jdbcType=INTEGER}")
    int updateByPrimaryKey(User record);

4.创建dao层(位于dao包)

public interface UserDao

5.创建impl实现(最好位于impl 包)

@Service("userService")
public class UserServiceImpl implements UserDao{
    @Autowired
    UserMapper userMapper;
    @Override
    public User getByUserNameAndPassword(User user) {
        User loginUser = userMapper.getByUserNameAndPassword(user);
        return loginUser;
    }
}

参考文章

1.Spring Boot整合MyBatis

上一篇 下一篇

猜你喜欢

热点阅读