springboot 集成mysql

springboot集成mysql很简单

maven配置

创建springboot时,选择这两个即可
springboot 集成mysql_第1张图片
生成的依赖

 <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>

springboot 配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

创建数据库表和实体

CREATE TABLE `admin` (
  `id` varchar(10) NOT NULL,
  `adminname` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
public class Admin {
    private String id;
    private String adminname;
    private String password;
}

测试类

public class MySpringBootApplicationTest {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Test
    public void mySqlTest(){
        String sql = "select id,adminname,password from admin";
        List<Admin> adminList = (List<Admin>) jdbcTemplate.query(sql,new RowMapper<Admin>(){
            @Override
            public Admin mapRow(ResultSet rs,int rowNum) throws SQLException {
                Admin admin = new Admin();
                admin.setId(rs.getString("id"));
                admin.setAdminname(rs.getString("adminname"));
                admin.setPassword(rs.getString("password"));
                return admin;
            }
        });
        System.out.println("查询成功");
        for (Admin ad: adminList
             ) {
            System.out.println("id:"+ad.getId()+"; name:"+ad.getAdminname()+"; pass:"+ad.getPassword());
        }
    }
}

JdbcTemplate:是通过jdbc连接数据库的工具类
@Resource 自动注入,通过这个注解,可以实例化jdbcTemplate对象
@Autowired 与@Resource的区别

你可能感兴趣的:(web,server)