springboot+Mybatis+mysql示例

https://start.spring.io

新建項目


spring.png

pom.xml 文件增加mysql和mybatis配置

        <!--mysql數(shù)據(jù)庫驅(qū)動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

刪除application.properties,使用yml配置
新增
application-dev.yml、application.ym 文件

dev文件中jdbc:mysql://localhost:3306/ 后跟的是數(shù)據(jù)庫名稱

數(shù)據(jù)中新增user表,并且插入數(shù)據(jù)

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'malone', '007');
INSERT INTO `user` VALUES ('2', 'oyl', '520');

新建User類

public class User {
    private Integer id;
    private String username;
    private String password;
    ...省略get set 
}

新建UserMapper

@Repository
public interface UserMapper {
    User getUser(int id);
}

新建UserService

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    public User getUser(int id){
        return userMapper.getUser(id);
    }
}

新建UserController

@RestController
@RequestMapping("/springboot")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id){
        return userService.getUser(id).toString();
    }
}

resources目錄下新增mapping文件夾,并且新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joy.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.joy.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="username" jdbcType="VARCHAR" property="username" />
        <result column="password" jdbcType="VARCHAR" property="password" />
    </resultMap>

    <select id="getUser" resultType="com.joy.entity.User">
        select * from user where id = #{id}
    </select>
</mapper>

啟動類Application,新增

@MapperScan("com.joy.mapper") 

瀏覽器輸入訪問地址:http://localhost:8080/springboot/getUser/1 即可成功運行。

項目地址:https://github.com/Malone1023/springboot_mybatis

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容