欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

构建spring-boot+mybatis项目

程序员文章站 2022-04-25 07:59:23
...

application.properties

#服务器端口号
server.port=8888


#数据库数据源配置 serverTimezone=UTC可能会报错事件问题
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver


#mybatis
#要解析的mapper路径
mybatis.mapper-locations=classpath:mapper/*.xml
#实体层的包路径
mybatis.type-aliases-package=com.rz.test.pojo

User实体类

package com.rz.test.pojo;

import lombok.Data;
import org.apache.ibatis.type.Alias;

//注释实体类
@Data
//给User类取别名
@Alias("user")
public class User {
    private Integer id;
    private String username;
    private String password;
}

DAO层(持久层)

package com.rz.test.dao;

import com.rz.test.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

//Dao层注解
@Repository
//通过mapper映射文件查询数据库
@Mapper
public interface TestDao {
    public List<User>  select();
}

Service层接口(业务逻辑层)

package com.rz.test.service;

import com.rz.test.pojo.User;

import java.util.List;

public interface TestService {
    public List<User> select();
}

Service层实现类

package com.rz.test.service;

import com.rz.test.dao.TestDao;
import com.rz.test.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//service层注解
@Service
public class TestServiceImpl implements TestService{

	//自动注入bean
    @Autowired
    TestDao testDao;
	
    @Override
    public List<User> select() {
        return testDao.select();
    }
}

控制层UserController

package com.rz.test.controller;


import com.rz.test.pojo.User;
import com.rz.test.service.TestService;
import com.rz.test.service.TestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Service;
import java.util.List;

//控制层注解
@RestController
public class UserController {
	//自动注入bean
    @Autowired
    TestServiceImpl testService;
	//接口映射
    @RequestMapping("/select")
    public List<User> select(){
        return testService.select();
    }
}

创建mapper.xml配置文件,写sql语句resource->mapper文件夹下面

<?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.rz.test.dao.TestDao">
    <select id="select" resultType="user">
        select * from t_user
    </select>
</mapper>

注意

如果改了包名,会导致主类无法加载,需在maven的plugins里面运行clean插件,再重构项目即可。也可在setting->这个路径:
构建spring-boot+mybatis项目
勾选上这几个:
构建spring-boot+mybatis项目
构建spring-boot+mybatis项目