1、MyBatis连接数据库实现增删改查
1.1、创建项目
file—new—project—Spring Initializr—next—输入相关信息(见下图)—next—相应的依赖(Web中的Spring WebSQL中的MyBatis Framework,MySQL Driver)—next—finish—在新的窗口打开
这里Project SDK会自动识别本机匹配的Java jdk 版本。
这里Java Version选择本机的Java jdk版本。
依赖这部分,我们选择web中的Spring Web(在网页中连接数据库并进行对数据库的增、删、改、查)和SQL中的MyBatis Framework(使用MyBatis编写),MySQL Driver(连接MySQL数据库)和Spring Data JDBC可以帮助我们自动生成所需的pom文件。
选择要放在什么地方。
1.2、修改pom文件
在pom文件中加入下面代码
<!..引入druid数据源..>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
1.3、编写application.yml,连接并监控数据库
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost/jpa?useUnicod=true&charaterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
监控数据库
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=50
- 用户名:root
- 用户密码:root
- url: jdbc:mysql://localhost/jpa?useUnicod=true&charaterEncoding=utf-8&serverTimezone=UTC中jpa为数据库表名。
- 默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源(数据源的相关配置都在DataSourceProperties里面)。
- 参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型。
1.4、创建并编写User,创建与数据库中相同的类
在com.atguigu.springboot处右键—new—Java Class
输入user.User
内容为:创建与数据库相匹配的类
package com.atguigu.springboot.user;
public class User {
private int id;
private String name;
private String email;
public User(){
}
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
",email=" + email + '\'' +
'}';
}
}
1.5、创建并编写UsweMapper,自己编写增、删、改、查的语句然后调用
创建方法同上输入mapper.UsweMapper
内容为
package com.atguigu.springboot.mapper;
import com.atguigu.springboot.user.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
@Repository
//指定这是一个操作数据库的mapper
@Mapper
public interface UserMapper {
编写查询语句
@Select("select * from tbl_user where id=#{id}")
public User getUserById(int id);
编写删除语句
@Delete("delete from tbl_user where id=#{id}")
public int deleteUserById(int id);
编写更改语句
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into tbl_user(id,name,email) values(#{id},#{name},#{email})")
public int insertUser(User user);
编写天骄语句
@Update("update tbl_user set id=#{id},name=#{name},email=#{email} where id=#{id}")
public int updateUser(User user);
}
1.6、创建并编写DruidConfig,整合Druid数据源
创建方法同上,输入chenjia.DruidConfig
内容如下:
package com.atguigu.springboot.chenjia;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
导入druid数据源
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
1.7、创建并编写UserController,调用自己编写的增、删、改、查语句,并将将HTTP Get 映射到 特定的处理方法上。
创建方法同上,输入controller.UserController
内容如下:
package com.atguigu.springboot.controller;
import com.atguigu.springboot.mapper.UserMapper;
import com.atguigu.springboot.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
查
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id) {
return userMapper.getUserById(id);
}
改
@ResponseBody
@GetMapping("/user")
public User insertUser(User user) {
userMapper.insertUser(user);
return user;
}
删
@GetMapping("/user1/{id}")
public String deleteUser(@PathVariable("id") int id) {
userMapper.deleteUserById(id);
return "删除成功";
}
增
@GetMapping("/user2")
public User updateUser( User user) {
userMapper.updateUser(user);
return user;
}
}
1.8、修改SringBoot06DataMybatisApplication文件
修改为:
package com.atguigu.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
1.9、报错问题
1.9.1、错误1
在poml文件中加入
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
1.9.2、错误2
提示信息表明数据库驱动com.mysql.jdbc.Driver’已经被弃用了、应当使用新的驱动com.mysql.cj.jdbc.Driver