手机购物网站 建站,网站建设网站制作网站设计,试用网建设网站,如何调用网站列表页概念
当我们使用传统的jdbc进行数据库与程序的连接时#xff0c;每一个操作都需要写一条sql语句#xff0c;并且没法调试和修改
jdbc连接数据库流程#xff1a;
创建数据库连接池DataSource获取数据库连接Connection执行带占位符的sql语句通过Connection创建操作对象Stat…概念
当我们使用传统的jdbc进行数据库与程序的连接时每一个操作都需要写一条sql语句并且没法调试和修改
jdbc连接数据库流程
创建数据库连接池DataSource获取数据库连接Connection执行带占位符的sql语句通过Connection创建操作对象Statement指定替换占位符的字段类型值使用Statement执行sql语句返回结果或更新的数量处理返回的结果释放资源
而MyBatis则是一个持久层框架可以使用xml或者注解来方便的进行数据库的操作
创建MyBatis项目 创建spring项目时勾选上面五个依赖 如果使用的是oracle数据库那么将MySQL Driver替换成Oracle Driver
在配置文件中配置数据库的连接信息
spring.datasource.urljdbc:mysql://127.0.0.1:3306/database?characterEncodingutf-8
spring.datasource.usernameroot
spring.datasource.password密码
spring.datasource.driver-class-namecom.mysql.cj.jdbc.DriverMyBatise是一个ORM框架会将查询到的数据与java中的类进行互相转化
配置MyBatis中的XML路径
MyBatis中使用XML来保存数据库的sql语句因此在配置文件中还要加上下面这条语句
mybatis.mapper-locationsclasspath:包名/*Mapper.xml例如
mybatis.mapper-locationsclasspath:mybatis/*Mapper.xml业务代码
创建用户信息类
package com.example.demo.entity;
import lombok.Data;
import java.time.LocalDateTime;Data
public class UserInfo {private int id;private String username;private String password;private String photo;private LocalDateTime createTime;private LocalDateTime updateTime;private int state;
}创建Mapper接口
package com.example.demo.mapper;import org.apache.ibatis.annotations.Mapper;
import com.example.demo.entity.UserInfo;
import org.apache.ibatis.annotations.Param;Mapper
public interface UserMapper {UserInfo getUserById(Param(user_id) Integer id);
}添加UserMapper.xml
?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//EN http://mybati
s.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.example.demo.mapper.UserMapperselect idgetUserById resultTypecom.example.demo.entity.UserInfoselect * from userinfo where id${user_id}/select
/mapper创建UserService
使用属性注入获取UserMapper对象调用其getUserById方法
package com.example.demo.service;import com.example.demo.entity.UserInfo;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;Service
public class UserService {Autowiredprivate UserMapper userMapper;public UserInfo getUserById(Integer id){return userMapper.getUserById(id);}
}
创建UserController
使用属性注入获取到UserService对象然后调用其getUserById方法
package com.example.demo.controller;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;RestController
RequestMapping(/user)
public class UserController {Autowiredpublic UserService userService;RequestMapping(/get-user-by-id)public UserInfo getUserById(Integer id){if(id null){return null;}return userService.getUserById(id);}
}
最终就可以在浏览器中获取到数据库中的数据了