MyBatis实现Mapper配置并查询数据

Mapper 作为 Java 方法和 SQL 语句之间的桥梁,来更好地去使用 SQL

 

准备数据源

创建

drop database if exists mybatis_demo;

create database mybatis_demo;

use mybatis_demo;

create table user (

id int auto_increment primary key,

username varchar(20),

age int,

score int

);

insert into user (id, username, age, score) values

(1,‘peter‘, 18, 100), (2,‘pedro‘, 24, 200),

(3,‘jerry‘, 28, 500), (4,‘mike‘, 12, 300),

(5,‘tom‘, 27, 1000);

 

在mybatis-config.xml配置文件中添加上对应的mapper配置

<!-- mapper配置 -->

<mappers>

    <mapper class="mapper.UserMapper"/>

</mappers>

 

新建mapper包并新建UserMapper.java类

package mapper;

public interface UserMapper {

String selectUsernameById(Integer id);

}

添加SQL语句

@Select("SELECT username FROM user WHERE id = #{id}")

 

测试类usertest.java

@SuppressWarnings({"Duplicates"})

public class UserTest {

public static void main(String[] args) throws IOException, SQLException {

InputStream configuration = Resources.getResourceAsStream("mybatis-config.xml");

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

SqlSession session = sqlSessionFactory.openSession();

UserMapper mapper = session.getMapper(UserMapper.class);

String username = mapper.selectUsernameById(1);

System.out.println("username: " + username);

session.close();

}

}

MyBatis实现Mapper配置并查询数据

上一篇:springboot 接口参数校验


下一篇:PAT 乙级 1018.锤子剪刀布 C++/Java