Spring连接数据库

Spring又来啦!

这次致力于使用Spring实现连接数据库

1、Spring连接数据库


//application.properties
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#?????false, ???????????????
spring.thymeleaf.cache=false

#?????
spring.datasource.url=jdbc:mysql://192.168.65.147:3306/aa?useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
# Mysql8.0???com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

userMapper.java

package com.example.studyspring.mapper;


import com.example.studyspring.Pojo.user;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface userMapper {
    @Results({
            @Result(property = "id" ,column="id"),
            @Result(property="name",column="name")
    })

    @Select("select * from test_one")
    List<user> getAll();

}

userService.java

package com.example.studyspring.service;

import com.example.studyspring.Pojo.user;
import com.example.studyspring.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class userService {

    @Autowired
    private userMapper um;

    public List<user> getAll(){
        return um.getAll();
    }
}


userController.java

package com.example.studyspring.Controller;

import com.example.studyspring.Pojo.user;
import com.example.studyspring.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 userController {
    @Autowired
    private userService us;

    @GetMapping("/getAll")
    public List<user> getAll(){
        return us.getAll();
    }
}

user.java

package com.example.studyspring.Pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class user {
    private Integer id;
    private String name;
}

数据结果从数据库里面被取出来啦!

posted @ 2023-04-20 01:17  yesyes1  阅读(16)  评论(0编辑  收藏  举报