002.打通数据库链路

1.配置数据库application.properties

spring.datasource.name=imooc_mall_datasource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc_mall?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=197366

2.Controller(UserController.java)

package com.imooc.mall.controller;

import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 描述:     用户控制器
 */
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/test")
    @ResponseBody
    public User personalPage() {
        return userService.getUser();
    }
}

3.Service(UserService.java  接口)

package com.imooc.mall.service;

import com.imooc.mall.model.pojo.User;

/**
 * 描述:     UserService
 */
public interface UserService {

    User getUser();
}

 

4.Service中impl(UserServiceImpl.java   实现类)

package com.imooc.mall.service.impl;

import com.imooc.mall.model.dao.UserMapper;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 描述:     UserService实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }
}

5.application.properties中告诉Mybatis   mapper文件在哪里找

mybatis.mapper-locations=classpath:mappers/*.xml

6.运行以后仍然报错

6.1   报错情况

 

 6.2 解决办法在主类中添加注解@MapperScan(basePackages = "com.imooc.mall.model.dao")

package com.imooc.mall;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.mall.model.dao")
public class MallApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(MallApplication.class, args);
    }

}

7.一个报错

 

 

 

 

 


posted @ 2022-11-05 23:13  李林林  阅读(41)  评论(0编辑  收藏  举报