Service与Dao如何在SpringBoot中使用 ?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
效果图
配置环境
创建数据库
数据库中文编码
建表
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); }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。