springboot的介绍与数据访问操作的几种方式

  • springboot介绍
    springboot的设计是为了使您能够尽可能快地启动和运行。它使用 “习惯优于配置” (项目中存在大量的配置,而 Spring Boot 内置一个习惯性的配置,让你无须手动进行配置)的理念让你的项目快速运行起来。使用 Spring Boot 很容易创建一个独立运行(运行jar,内嵌 Servlet 容器)、准生产强力的基于 Spring 框架的项目,使用 Spring Boot你可以不用或者只需要很少的 Spring 配置。提供了 J2EE开发的一站式解决方案。

  • springboot优点

  • 快速构建独立运行的Spring项目;(速度快)

  • 无须依赖外部Servlet容器,应用无需打成WAR包;项目可以打成jar包独自运行;

  • 提供 一系列 starter pom 来简化 Maven 的依赖加载;(简化依赖加载)

  • 大量的自动配置,对主流开发框架的无配置集成;(无配置)

  • 无须配置XML,开箱即用,简化开发,同时也可以修改默认值来满足特定的需求;

  • Spring Boot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式;极大提高了开发、部署效率。
    上面简单描述了springboot的概要与优点,接下类我们要了解一下springboot数据访问操作的几种方式。

  • springboot数据访问操作的方式:

  • 使用JDBC

    导入jdbc启动器
    在这里插入图片描述
    配置application.yml文件

spring:
	datasource:
		username: root
		password: root
		#使用 MySQL连接驱动是8.0以上,需要在Url后面加上时区, GMT%2B8代表中国时区,不然报时区错误
		url: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8
		# 注意: 新版本驱动包,要使用以下类作为驱动类
		driver-class-name: com.mysql.cj.jdbc.Driver

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDataApplicationTests {
	@Autowired
	DataSource datasource;
	@Test
	public void contextLoads() throws SQLException {
		// 默认采用的数据源连接池:com.zaxxer.hikari.HikariDataSource
		System.out.println("datasource: " + datasource.getClass());
		Connection connection = datasource.getConnection();
		System.out.println(connection);
		connection.close();
	}
}

以上测试发现:

  1. SpringBoot 默认采用的数据源连接池是: com.zaxxer.hikari.HikariDataSource
  2. 数据源相关配置都在 DataSourceProperties 中;

JDBC自动配置类JdbcTemplateAutoConfiguration提供了JdbcTemplate模板类来操作数据库

@Controller
public class ProviderController {
	@Autowired
	JdbcTemplate jdbcTemplate;
	@ResponseBody
	@GetMapping("/providers")
	public Map<String, Object>list() {
		List<Map<String, Object>> maps =
		jdbcTemplate.queryForList("select * from provider");
		System.out.println(maps);
		return maps.get(0);
	}
}

springboot默认采用的数据源是Hikari,Hikari数据源性能上比Druid好,但是Druid数据源有配套的监控安全管理功能,下面我们更换springboot的数据源为Druid。

  1. 导入Druid依赖
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.12</version>
</dependency>
  1. Druid 全局配置
spring:
	datasource:
		# 数据源基本配置
		username: root
		password: root
		url: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8
		# 8.x版本驱动包,要使用以下类作为驱动类
		driver-class-name: com.mysql.cj.jdbc.Driver
		# 指定 Druid 数据源
		type: com.alibaba.druid.pool.DruidDataSource
		# 数据源其他配置, DataSourceProperties中没有相关属性,默认无法绑定
		initialSize: 8
		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,logback
		maxPoolPreparedStatementPerConnectionSize: 25
		useGlobalDataSourceStat: true
		connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

经过以上配置数据源已经切换为DruidDataSource
3. 自定义Druid配置类,将配置中的属性与DruidDataSource属性绑定

package com.mengxuegu.springboot.config;

/**
* Druid 配置类
* @Auther: xiaomingjun
*/
@Configuration
public class DruidConfig {
	//绑定数据源配置
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druid() {
		return new DruidDataSource();
	}
}
  1. 配置Druid监控
package com.mengxuegu.springboot.config;

/**
 * Druid 配置类
 * @Auther: xiaomingjun
*/
@Configuration
public class DruidConfig {
	//绑定数据源配置
	@ConfigurationProperties(prefix = "spring.datasource")
	@Bean
	public DataSource druid() {
		return new DruidDataSource();
	}
	/**
	* 配置Druid监控
	* 1. 配置一个管理后台的Servlet
	* 2. 配置一个监控的filter
	*/
	@Bean // 1. 配置一个管理后台的Servlet
	public ServletRegistrationBean statViewServlet() {
		//StatViewServlet是 配置管理后台的servlet
		ServletRegistrationBean<StatViewServlet> bean =
		new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
		//配置初始化参数
		Map<String, String> initParam = new HashMap<>();
		//访问的用户名密码
		initParam.put(StatViewServlet.PARAM_NAME_USERNAME, "root");
		initParam.put(StatViewServlet.PARAM_NAME_PASSWORD, "123");
		//允许访问的ip,默认所有ip访问
		initParam.put(StatViewServlet.PARAM_NAME_ALLOW, "");
		//禁止访问的ip
		initParam.put(StatViewServlet.PARAM_NAME_DENY, "192.168.10.1");
		bean.setInitParameters(initParam);
		return bean;
	}
	//2. 配置一个监控的filter
	@Bean
	public FilterRegistrationBean filter() {
		FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
		bean.setFilter(new WebStatFilter());
		//配置初始化参数
		Map<String, String> initParam = new HashMap<>();
		//排除请求
		initParam.put(WebStatFilter.PARAM_NAME_EXCLUSIONS, "*.js,*.css,/druid/*");
		//拦截所有请求
		bean.setUrlPatterns(Arrays.asList("/*"));
		return bean;
	}
}
  • 使用mybatis注解版
    在这里插入图片描述
  1. 导入Druid数据源依赖
<!--druid数据源-->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.12</version>
</dependency>
  1. 配置Druid数据源,以上操作一样
  2. mapper接口层使用注解直接使用sql语句访问数据库
package com.mengxuegu.springboot.mapper;
import com.mengxuegu.springboot.entities.Provider;
import org.apache.ibatis.annotations.*;
/**
* 使用Mybatis注解版本
* @Auther: xiaomingjun
*/
//@Mapper //指定这是操作数据的Mapper
public interface ProviderMapper {
	@Select("select * from provider where pid=#{pid}")
	Provider getProvierByPid(Integer pid);
	//useGeneratedKeys是否使用自增主键,keyProperty指定实体类中的哪一个属性封装主键值
	@Options(useGeneratedKeys = true, keyProperty = "pid")
	@Insert("insert into provider(providerName) values(#{providerName})")
	int addProvider(Provider provider);
	@Delete("delete from provider where pid=#{pid}")
	int deleteProviderByPid(Integer pid);
	@Update("update provider set providerName=#{providerName} where pid=#{pid}" )
	int updateProvider(Provider provider);
}

注意:
上面@Insert插入数据时, 使用 @Options 接收插入的主键值:
useGeneratedKeys是否自增主键, keyProperty指定实体中哪个属性封装主键
@Options(useGeneratedKeys = true, keyProperty = “pid”)

  1. 控制层调用mapper接口层的方法
@Controller
public class ProviderController {
	@Autowired
	ProviderMapper providerMapper;
	@ResponseBody
	@GetMapping("/provider/{pid}")
	public Provider getProvider(@PathVariable("pid") Integer pid) {
		Provider providerByPid = providerMapper.getProviderByPid(pid);
		return providerByPid;
	}
	@ResponseBody
	@GetMapping("/provider")
	public Provider addProvider(Provider provider) {
		providerMapper.addProvider(provider);
	return provider;
}
  1. 自定义mybatis配置类,来替换mybatis配置文件
    开启驼峰命名方式
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.apache.ibatis.session.Configuration;
/**
* MyBatis注解版-配置类替换配置文件
* @Auther:xiaomingjun
*/
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
	@Bean
	public ConfigurationCustomizer configurationCustomizer() {
		return new ConfigurationCustomizer(){
			@Override
			public void customize(Configuration configuration) {
				//开启驼峰命名方式
				configuration.setMapUnderscoreToCamelCase(true);
			}
		};
	}
}
  1. 在启动类上加@MapperScan("")注解,该注解会自动扫描指定包下面的所有mapper,省得在每一个mapper接口上加@Mapper注解
//会自动装配指定包下面所有Mapper,省得在每个Mapper上面写@Mapper
@MapperScan("com.mengxuegu.springboot.mapper")
@SpringBootApplication
public class SpringBoot08DataMybatisApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringBoot08DataMybatisApplication.class, args);
	}
}
  • 使用mybatis配置文件版
  1. mapper接口
/**
* MyBatis 配置文件版
* @Auther:xiaomingjun
*/
//@Mapper 或 @MapperScan 扫描Mapper接口装配到容器中
public interface BillMapper {
	Bill getBillByBid(Integer bid);
	int insertBill(Bill bill);
}
  1. 在resources创建以下目录和核心配置文件与Mapper映射文件
    在这里插入图片描述
    mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
	PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
	<configuration>
		<!--mybatis核心配置文件-->
		<settings>
			<!--开启驼峰命名-->
			<setting name="mapUnderscoreToCamelCase" value="true"/>
		</settings>
	</configuration>

BillMapper映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
	PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
	<mapper namespace="com.mengxuegu.springboot10datamybatis.entities">
		<select id="getBillByBid"
			resultType="com.mengxuegu.springboot10datamybatis.entities.Bill">
			select * from bill where bid = #{bid}
		</select>
	<insert id="addBill">
		insert into bill(bill_code, bill_name) values(#{billCode}, #{billName})
	</insert>
</mapper>
  1. 在application.yml中指定配置文件路径
# Mybatis相关配置
mybatis:
	#核心配置文件路径
	config-location: classpath:mybatis/mybatis-config.xml
	#映射配置文件路径
	mapper-locations: classpath:mybatis/mapper/*.xml
# 打印sql
logging:
	level:
		com.mengxuegu.springboot10datamybatis.mapper : debug
  1. 创建BillController来测试
@Controller
public class BillController {
	@Autowired
	BillMapper billMapper;
	@ResponseBody
	@GetMapping("/bill/{bid}")
	public Bill getBill(@PathVariable Integer bid) {
		return billMapper.getBillByBid(bid);
	}
	@ResponseBody
	@GetMapping("/bill")
	public Bill addBill(Bill bill) {
		billMapper.addBill(bill);
		return bill;
	}
}
  • 使用spring data jpa
  1. 什么是spring data?
    Spring Data 是 Spring Boot 底层默认进行数据访问的技术 , 为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、Map-Reduce 框架、云数据服务等;另外也包含对关系数据库的访问支持。
    Spring Data 包含多个模块:
    Spring Data Commons 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化
    Spring Data JPA
    Spring Data KeyValue
    Spring Data LDAP
    Spring Data MongoDB
    Spring Data Redis
    Spring Data REST
    Spring Data for Apache Cassandra
    Spring Data for Apache Geode
    Spring Data for Apache Solr
    Spring Data for Pivotal GemFire
    Spring Data Couchbase (community module)
    Spring Data Elasticsearch (community module)
    Spring Data Neo4j (community module)
  2. spring data 特点?
    Spring Data 项目为大家提供统一的API来对不同数据访问层进行操作;
    Spring Data 统一的核心接口
    Repository :统一的根接口,其他接口继承该接口
    CrudRepository :基本的增删改查接口,提供了最基本的对实体类CRUD操作
    PagingAndSortingRepository :增加了分页和排序操作
    JpaRepository :增加了批量操作,并重写了父接口一些方法的返回类型
    JpaSpecificationExecutor :用来做动态查询,可以实现带查询条件的分页(不属于Repository体系,支持 JPA Criteria 查询相关的方法 )
  3. spring data jpa、jpa与Hibernate的关系?
    在这里插入图片描述
    JPA是一种规范,而Hibernate是实现这种规范的底层实现,Spring Data JPA对持久化接口 JPA 再抽象一层,针对持久层业务再进一步统一简化。
  4. 整合Spring Data JPA实战
    JPA的底层遵守是ORM(对象关系映射)规范,因此JPA其实也就是java实体对象和关系型数据库建立起映射关系,通过面向对象编程的思想操作关系型数据库的规范。
    在这里插入图片描述
    配置application.yml文件,添加数据源
spring:
	datasource:
		# 数据源基本配置
		username: root
		password: root
		url: jdbc:mysql://127.0.0.1:3306/jpa?serverTimezone=GMT%2B8
		# 8.x版本驱动包,要使用以下类作为驱动类
		driver-class-name: com.mysql.cj.jdbc.Driver

创建实体类,使用JPA注解进行配置映射关系
类上使用JPA注解@Entity标注,该注解作用是说明该类是和数据表映射的类;
@Table(name=“表名”)指定对应映射的表名,省略时默认类名就是表名。
@Id标识主键,@GeneratedValue(strategy=GenerationType.IDENTITY)标注该主键是自增主键
@Column标识字段

import javax.persistence.*;
//使用JPA注解进行配置映射关系
@Entity //说明它是和数据表映射的类
@Table(name = "tbl_user") //指定对应映射的表名,省略默认表名就是类名
public class User {
	@Id //标识主键
	@GeneratedValue(strategy = GenerationType.IDENTITY) //标识自增长主键
	private Integer id;
	@Column(name = "user_name",length = 5) //这是和数据表对应的一个列
	private String userName;
	@Column //省略默认列名就是属性名
	private String password;
	setter/getter
}

创建UserRepository接口继承JpaRepository,该接口就具备了crud及分页等基本功能了。

package com.mengxuegu.springboot.dao;
import com.mengxuegu.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 自定义接口继承JpaRepository,就会crud及分页等基本功能
* @Auther: 梦学谷 www.mengxuegu.com
*/
//指定的泛型<操作的实体类,主键的类型>
public interface UserRepository extends JpaRepository<User, Integer> {
}

在application.yml文件中配置JPA

spring:
	datasource:
		# 数据源基本配置
		username: root
		password: root
		url: jdbc:mysql://127.0.0.1:3306/jpa
		# 8.x版本驱动包,要使用以下类作为驱动类
		driver-class-name: com.mysql.cj.jdbc.Driver
	# jpa相关配置 spring.jpa.*
	jpa:
		# 控制台显示SQL
		showSql: true
		hibernate:
			# 会根据就映射实体类自动创建或更新数据表
			ddl-auto: update
		# 默认创建表类型是MyISAM,是非事务安全的,所以无法实现事物回滚
		# 指定如下方言: 创建的表类型是Innodb,才可以进行对事物的回滚。
		database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

在控制层中来调用刚才创建的UserRepository接口实现crud功能

@RestController
public class UserController {
	@Autowired
	UserRepository userRepository;
	@GetMapping("/user/{id}")
	public User getUserById(@PathVariable("id") Integer id) {
		return userRepository.findById(id).get();
	}
	@GetMapping("/user")
	public User addUser(User user) {
		return userRepository.save(user);
	}
}

至此springboot简单介绍与springboot的几种数据访问方式已经完成了。
非常感谢读者们的阅览,希望大家能够在快乐中学习,快速地掌握。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值