栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mybatis操作数据库

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mybatis操作数据库

1.引入第三方工具mybatis的场景启动器
y

如果有错误可以根据Ide提示修改

2.在resources下建立mybatis文件写入mybatis-config.xml全局配置文件




      
             //开启驼峰命名规则
      

再在mybatis下建立mapper文件夹,放入AccountMapper.xml文件,用于映射操作数据库




    
        select * from student where id = #{id}
    

3.在bean下写一个Acount类封装student表中的信息,如下

package com.ml.admin.bean;

import lombok.Data;

@Data
public class Account {
    private Integer id;
    private String name;
    private  Integer age;
}

4.在mapper文件下写一个AccountMapper接口操作数据表student表,如下

@Mapper
public interface AccountMapper {
   public Account getAccount_id(Integer id);
}

5.在application.yaml中配置mybatis映射规则

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml  #全局配置文件路径
  mapper-locations: classpath:mybatis/mapper/*.xml   #sql映射文件路径

6.在service下创建AccountService.java文件用于实现AccountMapper接口,如下

package com.ml.admin.service;

import com.ml.admin.bean.Account;
import com.ml.admin.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountService {
    @Autowired
    AccountMapper accountMapper;


    public Account get_by_id(Integer id) {
        return accountMapper.getAccount_id(id);
    }


}

7.使用@ResponseBody返回查询数据,代码如下

@Autowired
    AccountService accountService;
    @ResponseBody   //用于返回json数据,要是没有这个页面就会解析错误
    @GetMapping("/account")
    public Account get_id(@RequestParam("id") Integer id){
        return accountService.get_by_id(id);

    }

student表

结果如下

注意
mybatis:
  #config-location: classpath:mybatis/mybatis-config.xml  #全局配置文件路径
  mapper-locations: classpath:mybatis/mapper/*.xml   #sql映射文件路径
  configuration:  # 和上面的全局配置文件只能存在一个,所以可以删除mybatis-config.xml文件
    map-underscore-to-camel-case: true


依旧访问正常

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/325412.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号