学习Spring boot第二阶段:Spring Boot JDBC访问数据库
前面已经用spring boot 搭建好了,可以用浏览器访问显示出“hello world”,今天一会再温习一遍
今天学习 “Spring Boot JDBC访问数据库“
idea 是 2021.3.3
SQL Server 是 2012
1、pom.xml添加依赖项:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>com.microsoft</groupId> <artifactId>sqljdbc4</artifactId> <version>3.0</version> </dependency>
2、application.properties中添加sql的连接信息:
#SQL server spring.datasource.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=xxx spring.datasource.username=sa spring.datasource.password=yyy spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver # xxx 你要访问的数据库 # yyy 你数据库的密码
下面来做一个测试的查询:
1、我们增加一个表,test:
2、添加几条数据:
3、新建一个javaweb的项目。
4、增加一个实体类,MyUser
package com.example.demo1.entity;
import lombok.Data;
@Data
public class MyUser {
public String name;
public String sex;
public Integer age;
}
注意:变量名称一定要和你数据库中的一致。
5、增加一个Repository接口,MyUserRepository
package com.example.demo1.repository;
import com.example.demo1.entity.MyUser;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MyUserRepository {
@Select("select * from test")
public List<MyUser> getAll();
}
6、创建接口,MyUserService
package com.example.demo1.service;
import com.example.demo1.entity.MyUser;
import java.util.List;
public interface MyUserService {
public List<MyUser> getAll();
}
7、实现这个接口,MyUserServiceImpl
package com.example.demo1.service;
import com.example.demo1.entity.MyUser;
import com.example.demo1.repository.MyUserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MyUserServiceImpl implements MyUserService{
private final MyUserRepository myUserRepository;
public MyUserServiceImpl(MyUserRepository myUserRepository){
this.myUserRepository = myUserRepository;
}
@Override
public List<MyUser> getAll() {
return myUserRepository.getAll();
}
}
8、创建个Control类,在web上查看:
package com.example.demo1;
import com.example.demo1.entity.MyUser;
import com.example.demo1.service.MyUserService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@MapperScan(basePackages = "com.example.demo1.repository")
public class CheckUser {
private final MyUserService myUserService;
public CheckUser(MyUserService myUserService){
this.myUserService = myUserService;
}
@RequestMapping("/getAll")
public List<MyUser> getAll(){
return myUserService.getAll();
}
}
ok,完!
浏览器效果:
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
使用stream流进行条件查询
