springboot整合mybatis

springboot整合mybatis_第1张图片

 

 

 

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.0version>
        dependency>

 

配置jdbc连接

#配置数据源   yml
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test_demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
    type: org.springframework.jdbc.datasource.DriverManagerDataSource
    #如果不指定数据源默认使用HikariDataSource
#配置mybatis的sql打印
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
 

 

 

创建user类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private Integer id;
    private String name;
    private String pwd;
}

 

UserMapper接口

import java.util.List;

@Mapper

public interface userMapper {
    //添加
    @Insert(value = "insert into test_user(name,pwd) values(#{name},#{pwd})")
    public void addUser(User user);
    //修改
    @Update(value = "update test_user set name=#{name},pwd=#{pwd} where id=#{id}")
    public void updateUser(User user);
    //删除
    @Delete(value = "delete from test_user where id=#{id}")
    public void deleteUser(@Param("id")Integer id);
    //查询一个
    @Select(value = "select * from test_user where id=#{id}")
    public User showOneUser(@Param("id")Integer id);
    //全查询
    @Select(value = "select * from test_user")
    public List showALLUser();
}

测试类

    @Qualifier("dataSource")
    @Autowired
    DataSource dataSource;

    @Autowired
    userMapper usermapper;

    @Test
    void contextLoads() {
        System.out.println(dataSource+"----------==");
    }

    @Test
    void testmybatis(){
        System.out.println(usermapper);
    }

    @Test
    void testShowOne(){
        User user =  usermapper.showOneUser(2);
        System.out.println(user);
    }

你可能感兴趣的:(springboot整合mybatis)