Java+mybatis

shenmingyang 发布于 2024-09-28 70 次阅读


环境配置

springboot项目先增加这几项依赖

创建application.yaml并填写mybatis相关配置

mybatis:
#classpath指的是resources文件,冒号后直接接mapper的xml配置文件
  mapper-locations: classpath:mapper/*.xml
#连接的是Java文件中的dao层,也就是数据访问层
  type-aliases-package: com.mybatis.dao
#针对大小写配对
  configuration:
    map-underscore-to-camel-case: true
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/数据表?serverTimezone=Asia/Shanghai
    username: root
    password: **********

项目文件结构

controller:控制层

dao:存放数据,一般用于对应数据库中的字段

mapper:存放mapper类文件,mapper类中的方法对应resource中的id字段

service:编写接口,内部方法需要对应mapper类中的方法

impl:里面的类将会继承service包的sever类,并且重写方法

编写相关层

package com.mybatis.mapper;

#mapper类(这里以用户类为示例)
import com.mybatis.dao.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
    List<User> findall();
}

package com.mybatis.service;

#UserService
import com.mybatis.dao.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserService {
    List<User> findall();
}
package com.mybatis.service.impl;

#UserServiceImpl
import com.mybatis.dao.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findall() {
        return userMapper.findall();
    }
}
package com.mybatis.dao;

#User
import lombok.Data;

@Data
public class User {
    private String name;
    private String password;
}
package com.mybatis.controller;

#Controller
import com.mybatis.dao.User;
import com.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class TestController {
    @Autowired
    private UserService userService;
    @GetMapping("/user")
    public List<User> test(){
        return userService.findall();
    }
}
<!--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.mybatis.mapper.UserMapper">
    <select id="findall" resultType="User">
        select * from userm
    </select>
</mapper>

以上为Java+mybatis的基本框架

此作者没有提供个人介绍
最后更新于 2024-10-30