文章目录
1、SpringBoot整合JDBC1.1、新建一个springboot项目1.2、在application.yml中写配置1.3、在Test里边进行测试1.5、结果1.4、编写controller
2、SpringBoot整合Druid2.1、导入依赖2.2、启动test测试类2.3、在application.yml中添加配置2.4、启动测试,查看结果2.5、自定义配置1、首先将yml中的配置绑定到DruidConfig中2、配置后台监控3、启动测试4、执行sql语句5、也可以自定义过滤器
3、SpringBoot整合Mybatis3.1、导入整合依赖3.2、编写连接数据库的配置3.3、在Test测试类中进行测试3.4、创建pojo实体类3.5、创建一个mapper接口,编写增删改查方法3.6、在resource下新建一个mappers目录,新建UserMapper.xml配置文件3.7、编写server层业务3.8、编写controller层业务
1、SpringBoot整合JDBC
1.1、新建一个springboot项目
1.2、在application.yml中写配置
spring:
datasource:
username: root
password: root
url: jdbc
:mysql
://localhost
:3306/mybatis
?serverTimezone=UTC
&useUnicode=false
&characterEncoding=utf
-8
driver-class-name: com.mysql.cj.jdbc.Driver
1.3、在Test里边进行测试
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
DataSource dataSource
;
@Test
void contextLoads() throws SQLException
{
System
.out
.println(dataSource
.getClass());
Connection connection
= dataSource
.getConnection();
System
.out
.println(connection
);
connection
.close();
}
}
1.5、结果
1.4、编写controller
注意使用@RestController注解,需要导入web启动依赖
<dependency>
<groupId>org
.springframework
.boot
</groupId
>
<artifactId>spring
-boot
-starter
-web
</artifactId
>
</dependency
>
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate
;
@GetMapping("/user")
public List
<Map
<String,Object>> userList(){
String sql
= "select * from user";
List
<Map
<String, Object>> mapList
= jdbcTemplate
.queryForList(sql
);
return mapList
;
}
@GetMapping("/add")
public String
addList(){
String sql
= "insert into user(id,name,pwd) values(7,'小王','1111')";
jdbcTemplate
.update(sql
);
return "插入成功";
}
@GetMapping("/update/{id}")
public String
updateList(@PathVariable("id") Integer id
){
String sql
= "update user set name=?,pwd=? where id="+id
;
Object
[] objects
= new Object[2];
objects
[0] = "张三";
objects
[1] = "123";
jdbcTemplate
.update(sql
,objects
);
return "修改成功";
}
@GetMapping("/delete/{id}")
public String
deleteList(@PathVariable("id") Integer id
){
String sql
= "delete from user where id = ?";
jdbcTemplate
.update(sql
,id
);
return "删除成功";
}
}
2、SpringBoot整合Druid
2.1、导入依赖
<!-- druid
-->
<dependency>
<groupId>com
.alibaba
</groupId
>
<artifactId>druid
</artifactId
>
<version>1.2.1</version
>
</dependency
>
2.2、启动test测试类
连接数据库的底层不会改变,都是JDBC,
改变数据源只需要在application.yml配置中做修改
type: com.alibaba.druid.pool.DruidDataSource
spring:
datasource:
username: root
password: root
url: jdbc
:mysql
://localhost
:3306/mybatis
?serverTimezone=UTC
&useUnicode=false
&characterEncoding=utf
-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
查看数据源:
2.3、在application.yml中添加配置
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: stat
,wall
,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
加入log4j依赖
<!-- log4j
-->
<dependency>
<groupId>log4j
</groupId
>
<artifactId>log4j
</artifactId
>
<version>1.2.17</version
>
</dependency
>
2.4、启动测试,查看结果
查询结果和JDBC没有区别,区别在于Druid可以自定义配置
2.5、自定义配置
新建config目录,在config目录下新建DruidConfig
一定要加@Configuration注解,否则无法生效
1、首先将yml中的配置绑定到DruidConfig中
@ConfigurationProperties(prefix
= "spring.datasource")
@Bean
public DataSource
druidDataSource(){
return new DruidDataSource();
}
2、配置后台监控
因为SpringBoot内置了servlet容器,所以没有web.xml
注意:一定要将配置注册到Bean中
@Bean
public ServletRegistrationBean
StatViewServlet(){
ServletRegistrationBean
<StatViewServlet> bean
= new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 根据源代码进行编写
HashMap
<String, String> initParameters
= new HashMap<>();
// 增加配置
// loginUsername
,loginPassword 参数是固定的
initParameters
.put("loginUsername","admin");
initParameters
.put("loginPassword","123");
// 允许谁可以访问
,也可以禁止谁访问
// 这里表示谁都可以访问
initParameters
.put("allow","");
// 设置初始化参数
bean
.setInitParameters(initParameters
);
return bean
;
}
3、启动测试
输入用户名,密码后效果:
4、执行sql语句
可以在Driud里边查看到sql
5、也可以自定义过滤器
@Bean
public FilterRegistrationBean
webStatFilter(){
FilterRegistrationBean
<Filter> bean
= new FilterRegistrationBean<>();
bean
.setFilter(new WebStatFilter());
HashMap
<String, String> initParameters
= new HashMap<>();
initParameters
.put("exclusions","*.js,*.css,/druid/*");
return bean
;
}
3、SpringBoot整合Mybatis
项目结构
新建一个springboot项目,勾选web,sql驱动,和sql API模块
3.1、导入整合依赖
<!-- mybatis
-spring
-boot
-starter
-->
<dependency>
<groupId>org
.mybatis
.spring
.boot
</groupId
>
<artifactId>mybatis
-spring
-boot
-starter
</artifactId
>
<version>2.1.3</version
>
</dependency
>
3.2、编写连接数据库的配置
spring
.datasource
.username
=root
spring
.datasource
.password
=root
spring
.datasource
.url
=jdbc
:mysql
://localhost
:3306/mybatis
?useUnicode
=false&serverTimezone
=UTC
&characterEncoding
=utf
-8
spring
.datasource
.driver
-class-name
=com
.mysql
.cj
.jdbc
.Driver
3.3、在Test测试类中进行测试
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Autowired
DataSource dataSource
;
@Test
void contextLoads() throws SQLException
{
System
.out
.println(dataSource
.getClass());
System
.out
.println(dataSource
.getConnection());
}
}
结果:
连接成功
3.4、创建pojo实体类
public class User implements Serializable {
private Integer id
;
private String name
;
private String pwd
;
}
3.5、创建一个mapper接口,编写增删改查方法
@Mapper
@Repository
public interface UserMapper {
List
<User> selectAllUser();
User
selectUserById(Integer id
);
int addUser(User user
);
int updateUser(User user
);
int deleteUser(Integer id
);
}
3.6、在resource下新建一个mappers目录,新建UserMapper.xml配置文件
第一种方式:
在编写xml配置文件前需要在application.properties中进行配置(起别名和扫描位置)
mybatis.type
-aliases
-package=com.jl.pojo
mybatis.mapper
-locations=classpath
:mappers/*.xml
第二种方式
@MapperScan("com.jl.mapper")
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jl.mapper.UserMapper">
<select id="selectAllUser" resultType="user">
select * from user;
</select>
<select id="selectUserById" resultType="user">
select * from user where id = #{id};
</select>
<insert id="addUser" parameterType="user">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="user">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser">
delete from user where id=#{id}
</delete>
</mapper>
3.7、编写server层业务
UserService
public interface UserService {
List
<User> selectAllUser();
User
selectUserById(Integer id
);
int addUser(User user
);
int updateUser(User user
);
int deleteUser(Integer id
);
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper
;
@Override
public List
<User> selectAllUser() {
return userMapper
.selectAllUser();
}
@Override
public User
selectUserById(Integer id
) {
return userMapper
.selectUserById(id
);
}
@Override
public int addUser(User user
) {
return userMapper
.addUser(user
);
}
@Override
public int updateUser(User user
) {
return userMapper
.updateUser(user
);
}
@Override
public int deleteUser(Integer id
) {
return userMapper
.deleteUser(id
);
}
}
3.8、编写controller层业务
@RestController
public class UserController {
@Autowired
private UserService userService
;
@GetMapping("/all")
public List
<User> selectAllUser(){
List
<User> userList
= userService
.selectAllUser();
for (User user
: userList
) {
System
.out
.println(user
);
}
return userList
;
}
@GetMapping("/id/{id}")
public User
selectUserById(@PathVariable("id") Integer id
){
User user
= userService
.selectUserById(id
);
System
.out
.println(user
);
return user
;
}
@GetMapping("/add")
public String
addUser(User user
){
userService
.addUser(new User(7,"jj","123"));
return "插入成功";
}
@GetMapping("/update")
public String
updateUser(User user
){
userService
.updateUser(new User(7,"hh","111"));
return "修改成功";
}
@GetMapping("/delete/{id}")
public String
deleteUser(@PathVariable("id") Integer id
){
userService
.deleteUser(7);
return "删除成功";
}
}
学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=32