要求:spring boot连接数据库读取数据
思想:通过spring boot去连接数据库,并创建实体类对象接收数据,JdbcTemplate去测试数据的读取
1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 引入jdbc支持 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- 连接MySQL数据库 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2.添加连接数据库i所需的属性
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/ljy?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password: 1234
3.创建pojo类
class User{ private int userId; private String name; private int age; public User(int userId, String name, int age){ this.userId = userId; this.name = name; this.age = age; } public int getUserId(){ return this.userId; } public String getName(){ return this.name; } public int getAge(){ return this.age; } public void setUserId(int userId){ this.userId = userId; } public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } }
4.测试连接
import pojo.User @RunWith(SpringRunner.class) @SpringBootTest public class MysqlApplicationTests { @Autowired private JdbcTemplate jdbcTemplate; @Test public void testJdbc() { List<Map<String, User>> maps = jdbcTemplate.queryForList("select * from user"); maps.forEach(System.out::println); } }
5.实验结果
运行输出:
{userid=1, name=ljy,age=21,}
{userid=2, name=djy, age=50,}