【MyBatis】

快速入门

1.准备springboot工程,数据库user表,实体类user

package org.example.pojo;

public class user {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "user{" +
                "name='" + name + '\'' +
                '}';
    }

    public user(String name) {
        this.name = name;
    }

    public user() {
    }
}

2.引入mybatis依赖并配置

pom.xml

        
            
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            3.0.2
        

        
            com.mysql
            mysql-connector-j
            runtime
            8.1.0
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            3.1.2
        

application.properties

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/user
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=123456

java接口 

package org.example.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper//会自动生成该接口的实现类对象,并且交给IOC容器管理
public interface UserMapper {
}

3.编写sql语句(注解和xml)

package org.example.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.example.pojo.user;

import java.util.List;

@Mapper//会自动生成该接口的实现类对象,并且交给IOC容器管理
public interface UserMapper {
    @Select("select * from user")
    public List list();
}

测试

package org.example;

import org.example.mapper.UserMapper;
import org.example.pojo.user;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testListUser() {
        List userList=userMapper.list();
        userList.stream().forEach(user->{
            System.out.println(user);
        });

    }
}

你可能感兴趣的:(mybatis,mybatis)