步骤:
添加jdbc的pom依赖application.yml中配置数据库信息 pom.xml添加Jdbc依赖 <!-- JDBC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- MySQL--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> application.yml中配置数据库信息注意:
mysql8需要配置时区信息(serverTimezone=UTC)mysql8驱动使用:com.mysql.cj.jdbc.DriverUTC:世界标准时间
# 涉及的类:DataSourceAutoConfiguration,DataSourceConfiguration,DataSourceProperties spring: datasource: username: root password: admin # 注意时区,mysql8需要 url: jdbc:mysql:///mall?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver 注入DataSource即可使用JDBC @SpringBootTest class SpringbootDataJdbc02ApplicationTests { @Autowired DataSource dataSource; @Autowired private JdbcTemplate jdbcTemplate; @Test void contextLoads() throws SQLException { // 查看默认的数据源 System.out.println(dataSource.getClass()); // 获取连接 Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } @Test void testJdbcTemplate(){ String sql = "select * from user"; List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql); System.out.println(maps); } }步骤:
添加druid的pom依赖在配置文件中修改spring.datasource.type添加druid配置信息编写druid配置类 添加pom依赖 <!-- 引入数据源:Druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> application.yml中添加druid配置 # 涉及的类:DataSourceAutoConfiguration,DataSourceConfiguration,DataSourceProperties spring: datasource: username: root password: admin # 注意时区,mysql8需要 url: jdbc:mysql:///mall?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver ###################druid配置########################### type: com.alibaba.druid.pool.DruidDataSource # 初始化连接池个数 initialSize: 5 # 最小连接池个数——》已经不再使用,配置了也没效果 minIdle: 2 # 最大连接池个数 maxActive: 20 # 配置获取连接等待超时的时间,单位毫秒,缺省启用公平锁,并发效率会有所下降 maxWait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 timeBetweenEvictionRunsMillis: 60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 minEvictableIdleTimeMillis: 300000 # 用来检测连接是否有效的sql,要求是一个查询语句。 # 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用 validationQuery: SELECT 1 FROM DUAL # 建议配置为true,不影响性能,并且保证安全性。 # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 testWhileIdle: true # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 testOnBorrow: false # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 testOnReturn: false # 打开PSCache,并且指定每个连接上PSCache的大小 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 # 通过别名的方式配置扩展插件,多个英文逗号分隔,常用的插件有: # 监控统计用的filter:stat # 日志用的filter:log4j # 防御sql注入的filter:wall filters: stat,wall,log4j # 通过connectProperties属性来打开mergeSql功能;慢SQL记录 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合并多个DruidDataSource的监控数据 useGlobalDataSourceStat: true druid配置类功能:
配置数据源,使用@Bean放入容器中,再使用@ConfigurationProperties注入配置文件中的信息注册Druid数据监控Servlet,使用ServletRegistrationBean 原因:由于springboot内置了Servlet,所以没有web.xml,这个类就相当于web.xml的作用 配置Druid数据监控Filter,同理 @Configuration public class DruidConfig { /** * 配置数据源,使用自定义好的配置 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } /** * 注册Druid数据监控Servlet */ @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> statViewServletBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); // 后台账号密码配置 HashMap<String, String> params = new HashMap<>(); // 账号密码设置,登录key是固定的 params.put("loginUsername","admin"); params.put("loginPassword","111"); // 允许谁可以访问,多个用逗号分割 params.put("allow","127.0.0.1"); // 禁止访问名单,多个用逗号分割 params.put("xuxu","192.168.11.12,192.168.1.13"); // 是否可以重置数据源,禁用HTML页面上的“Reset All”功能 params.put("resetEnable", "false"); statViewServletBean.setInitParameters(params); return statViewServletBean; } @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(); bean.setFilter(new WebStatFilter()); // 所有请求进行监控处理 bean.addUrlPatterns("/*"); // 可以设置过滤哪些请求 bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*"); return bean; } }步骤:
pom.xml中添加mybatis依赖application.yml配置mybatis整合信息 pom.xml中添加mybatis依赖idea中使用Spring initializr,勾选模块可快速创建
<!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> application.yml配置数据库和mybatis整合信息 # 数据库配置 spring: datasource: username: root password: admin url: jdbc:mysql:///eesy?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver # 整合mybatis mybatis: # 别名 type-aliases-package: top.roise.pojo # xxxMapper.xml文件位置 mapper-locations: classpath:mybatis/mapper/*.xml 编写实体类和MapperUser
@Data @NoArgsConstructor @AllArgsConstructor public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; }UserMapper
@Mapper:标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中
@Mapper @Repository public interface UserMapper { List<User> findUsers(); User findUserById(int id); void insertUser(User user); int updateUser(User user); int deleteUser(int id); }UserMapper.xml
<?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="top.roise.mapper.UserMapper"> <!-- 插入用户--> <insert id="insertUser" parameterType="top.roise.pojo.User"> insert into user values(#{id},#{username},#{birthday},#{sex},#{address}) </insert> <!-- 更新用户--> <update id="updateUser" parameterType="user"> update user set username=#{username} where id = #{id} </update> <!-- 删除用户--> <delete id="deleteUser" parameterType="int"> delete from user where id = #{id} </delete> <!-- 查询所有用户--> <select id="findUsers" resultType="top.roise.pojo.User" > select * from user </select> <!-- 根据id查找用户--> <select id="findUserById" resultType="top.roise.pojo.User"> select * from user where id = #{id}; </select> </mapper>主要使用@Select,@Delete,@Insert,@Update这四个注解
示例:mapper类
@Repository @Mapper public interface EmployeeDao { // @Options():要求主键递增 @Insert("insert into employee(last_name,email,gender,department_id,birth) values(#{lastName},#{email},#{gender},#{department.id},#{birth})") @Options(useGeneratedKeys = true, keyProperty = "id") void save(Employee employee); @Select("select * from employee") @ResultMap("employeeMap") List<Employee> getEmplyees(); @Select("select * from employee where id = #{id}") @Results(id = "employeeMap",value = { @Result(id = true,column = "id",property = "id"), @Result(column = "last_name",property = "lastName"), @Result(column = "email",property = "email"), @Result(column = "gender",property = "gender"), @Result(column = "department_id",property = "department",one = @One(select = "roise.top.mapper.DepartmentDao.getDepartment",fetchType = FetchType.EAGER)), @Result(column = "birth",property = "birth",javaType = Date.class) }) Employee get(Integer id); @Delete("delete from employee where id = #{id}") void delete(Integer id); }然后就可以直接使用了
关于mybatis注解的使用可参考:mybatis-注解
补充:添加元素时,需要自增主键
@Options(useGeneratedKeys = true, keyProperty = "id")注意:如果是jdk9,执行报错如下:
原因:jdk缺少相应的jar
解决方案:手动导入对应的maven坐标,如下:
<!--jdk9需要导入如下坐标--> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency>步骤:
添加redis的起步依赖配置redis的连接信息编写Redis配置类 添加redis的起步依赖 <!-- 配置使用redis启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 配置redis的连接信息 #Redis redis: #redis服务器地址 host: 192.168.0.102 #redis连接端口号 port: 6379 #redis连接密码 password: 199611 #redis连接超时时间(毫秒) timeout: 18000 lettuce: pool: # 连接池最小空闲连接 min-idle: 1 # 连接池最大空闲连接 max-idle: 10 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1 # 连接池最大连接数(使用负值表示没有限制) max-active: -1 书写Redis配置类 @Configuration public class RedisConfig extends CachingConfigurerSupport { /** * 自定义redisTemplate方法 */ @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // value序列化方式采用jackson template.setValueSerializer(jacksonSeial); // key采用String的序列化方式 template.setKeySerializer(new StringRedisSerializer()); // 对hash的key采用String的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); // 对hash的value采用jackson的序列化方式 template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } } 注入RedisTemplate测试redis操作 @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootJpaApplication.class) public class RedisTest { @Autowired private UserRepository userRepository; @Autowired private RedisTemplate<String, String> redisTemplate; @Test public void test() throws JsonProcessingException { //从redis缓存中获得指定的数据 String userListData = redisTemplate.boundValueOps("user.findAll").get(); //如果redis中没有数据的话 if(null==userListData){ //查询数据库获得数据 List<User> all = userRepository.findAll(); //转换成json格式字符串 ObjectMapper om = new ObjectMapper(); userListData = om.writeValueAsString(all); //将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库 redisTemplate.boundValueOps("user.findAll").set(userListData); System.out.println("===============从数据库获得数据==============="); }else{ System.out.println("===============从redis缓存中获得数据==============="); } System.out.println(userListData); } }