Files
inmind_web_project250915/springboot-mybatis-quickstart/src/test/java/com/inmind/SpringbootMybatisQuickstartApplicationTests.java
xuxin 4040b06ab8 1.lombok的使用
2.Spring-mybatis-增删改查准备工作
2025-09-25 14:34:50 +08:00

67 lines
2.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind;
import com.inmind.mapper.UserMapper;
import com.inmind.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest //该注解的作用启动spring环境所以也就有了IOC容器
class SpringbootMybatisQuickstartApplicationTests {
@Autowired//直接从IOC容器中获取UserMapper类型的对象
private UserMapper userMapper;//接口开发,多态
@Test
void contextLoads() {
//使用mybatis框架查询所有用户的数据
List<User> list = userMapper.list();
list.stream().forEach(user -> {
System.out.println(user.getId());
System.out.println(user);
});
}
@Test
void testJDBC() throws ClassNotFoundException, SQLException {
//1. 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 获取连接对象
String url = "jdbc:mysql://localhost:3306/mybatis";
String username = "root";
String password = "1234";
Connection connection = DriverManager.getConnection(url, username, password);
//3. 获取执行SQL的对象Statement,执行SQL,返回结果
String sql = "select * from user";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
//4. 封装结果数据
List<User> userList = new ArrayList<>();
while (resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
short gender = resultSet.getShort("gender");
String phone = resultSet.getString("phone");
User user = new User(id,name,age,gender,phone);
userList.add(user);
}
//5. 释放资源
statement.close();
connection.close();
userList.forEach(System.out::println);
}
}