首页 > 其他分享 >006.完成service和dao的编写

006.完成service和dao的编写

时间:2022-11-05 18:12:52浏览次数:56  
标签:service spring dao id 006 mysql public datasource

1.引入依赖

         <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.编写application.properties中和数据库相关的代码

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/interview?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=197366

3.新建service

/**
 * 描述:     查询学生信息Service
 */
@Service
public class StudentService
{

    @Autowired
    StudentMapper studentMapper;

    public Student getStudent(Integer id) {
        return studentMapper.findById(id);
    }
}

4.新建mapper(要和pojo中Strdent.java的字段映射)

/**
 * 描述:     TODO
 */
@Mapper
@Repository
public interface StudentMapper
{
    @Select("SELECT * FROM students WHERE id = #{id}")
    Student findById(long id);
}

5.新建Controller

/**
 * 描述:     学生Controller
 */
@RestController
public class StudentController
{

    @Autowired
    StudentService studentService;

    @GetMapping("/student")
    public String requestPara(@RequestParam Integer id) {
        return studentService.getStudent(id).toString();
    }
}

6.测试

 

 

 

 7.数据库建表语句

CREATE TABLE `students` (
  `id` int(11) NOT NULL,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

 

标签:service,spring,dao,id,006,mysql,public,datasource
From: https://www.cnblogs.com/LLL0617/p/16860753.html

相关文章