创建MySQL
1、打开HeidiSQL
2、输入密码 点击开打
3、新建一个名为restaurant的数据库 点击确定
4、 在restaurant数据库中创建名为user的数据表,并且添加数据 点击保存
5、数据表创建成功
使用JAVA查询MySQL
1、在Maven中的pom.xml中添加MySQL查询语句 点击刷新按钮
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
2、在com.school下创建一个mapper的包
3、在mapper包下新建一个接口UserMapper,添加以下代码
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT `name` FROM user WHERE id = #{id}")
public String selectManmeById(long id);
}
4、在rescourcs下新建一个file的yml文件 命名为application.yml
5、在.yml中添加以下代码
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/restaurant?serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6、在controller下新建一个UserController类 并添加如下代码
import com.school.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("getName")
public String getName(Long id){
return userMapper.selectManmeById(id);
}
}