SpringBoot Service和Dao的編寫詳解
阿新 • • 發佈:2020-11-24
本文主要介紹了SpringBoot Service和Dao的編寫詳解,分享給大家,具體如下:
效果圖
配置環境
建立資料庫
資料庫中文編碼
建表
create table `student` ( `id` int(11) Not NULL AUTO_INCREMENT COMMENT '主鍵自增id',`name` varchar(250) NOT NULL DEFAULT ' ' COMMENT '姓名',PRIMARY KEY(`id`) )ENGINE=INNODB DEFAULT CHARSET=utf8;
pom依賴和配置
mybatis 和 mysql
<!-- connect--> <!-- 不同版本mybatis對應boot版本不同--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <!-- mysql版本可以不指定--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
application.properties
# mysql spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/rxguo_test?serverTimezone=UTC&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=
java bean
package com.bennyrhys.com.shop.bean; public class Student { Integer id; String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student{" + "id=" + id + ",name='" + name + '\'' + '}'; } }
Controller
package com.bennyrhys.com.shop; import com.bennyrhys.com.shop.bean.Student; import com.bennyrhys.com.shop.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class StudentController { @Autowired StudentService studentService; @GetMapping("/student") public String getStudentById(@RequestParam Integer id) { Student student = studentService.getStudentById(id); return student.toString(); } }
Service
package com.bennyrhys.com.shop.service; import com.bennyrhys.com.shop.bean.Student; import com.bennyrhys.com.shop.mapper.StudentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentService { @Autowired StudentMapper studentMapper; public Student getStudentById(Integer id) { return studentMapper.getStudentById(id); } }
Mapper介面
package com.bennyrhys.com.shop.mapper; import com.bennyrhys.com.shop.bean.Student; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; @Mapper @Repository public interface StudentMapper { @Select("select * from student where id = #{id}") Student getStudentById(Integer id); }
到此這篇關於SpringBoot Service和Dao的編寫詳解的文章就介紹到這了,更多相關SpringBoot Service和Dao編寫內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!