springboot学习----8.数据访问

数据访问

对于数据访问层,无论是SQL还是NOSQL,springboot默认采用高整合springdata的方式进行统一处理,添加大量自动配置,屏蔽了很多设置,引入xxxTemplate,xxxRepository来简化我们对数据访问层的操作,对我们来说只需要进行简单的设置即可.

jdbc

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/db003?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
@SpringBootTest
class BootApplicationTests {

    @Autowired
    private DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass()); //class com.zaxxer.hikari.HikariDataSource
        Connection connection = dataSource.getConnection();
        System.out.println(connection); //HikariProxyConnection@1062254208 wrapping com.mysql.cj.jdbc.ConnectionImpl@54db056b
        connection.close();
    }

}

springboot的jdbc自动配置:
DataSourceAutoConfiguration:
DataSourceInitializer:ApplicationListener
作用:

  1. runSchemaScripts():运行建表语句
  2. runDataScripts():运行插入数据的sql语句
    默认只需要将文件命名为:schema.sql,schema-all.sql,或者data.sql,data-all.sql
    自动配置了jdbcTemplate来操作数据库
    引用Druid数据源:
    在application.yml中配置:
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=500

编写配置类使用我们自己的配置:

@Configuration
public class DruidConfig {

	//从全局配置文件中加载指定配置
	@Bean
	@ConfigurationProperties(prefix="spring.datasource")
	public DataSource myDruid() {
		return new DruidDataSource();
	}
	//配置Druid的监控
	/**
	 * 1.配置一个管理后台的Servlet
	 */
	@Bean
	public ServletRegistrationBean<Servlet> statViewServlet(){
		ServletRegistrationBean<Servlet> sgb = new ServletRegistrationBean<Servlet>(
				new StatViewServlet(),"/druid/*");
		Map<String,String> map = new HashMap<>();
		//设置一些初始化参数
		map.put("loginUsername", "root");
		map.put("loginPassword","123456");
		//默认允许所有访问
		map.put("allow", "");
		map.put("deny","192.168.1.11");
		sgb.setInitParameters(map);
		return sgb;
	}
	
	/**
	 * 2.配置一个监控的Filter
	 */
	@Bean
	public FilterRegistrationBean<Filter> webStatFilter(){
		FilterRegistrationBean<Filter> fgb = new FilterRegistrationBean<Filter>();
		Filter filter = new WebStatFilter();
		fgb.setFilter(filter);
		Map<String,String> map = new HashMap<>();
		map.put("exclusions", "*.jsp,*.css,*.js,/druid/*");
		fgb.setInitParameters(map);
		fgb.setUrlPatterns(Arrays.asList("/*"));
		return fgb;
	}
}


可以发现是能够正常进入后台管理页面的:
springboot学习----8.数据访问_第1张图片

mybatis

导入pom依赖:

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>
		<!-- 引入druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
	</dependencies>

编写mapper:

@Mapper
public interface DepartmentMapper {

	@Select("select * from department where id=#{id}")
	public Department getDeptById(Integer id);
	
	@Delete("delete from department where id=#{id}")
	public int deleteDeptById(Integer id);
	
	/**
	 * 封装主键属性
	 * @param department
	 * @return
	 */
	@Options(useGeneratedKeys = true,keyProperty = "id")
	@Insert("insert into department(department_name) values(#{departmentName})")
	public int insertDept(Department department);
	
	@Update("update department set department_name=#{department.departmentName} where id=#{department.id}")
	public int updateDept(Department department);
}

当然也可以自定义mybatis的配置规则:

@Configuration
public class MybatisConfig {

	/**
	 * 自定义mybatis配置
	 * @return
	 */
	@Bean
	public ConfigurationCustomizer configurationCustomizer() {
		return new ConfigurationCustomizer() {
			
			@Override
			public void customize(org.apache.ibatis.session.Configuration configuration) {
				configuration.setMapUnderscoreToCamelCase(true);
				System.out.println(configuration);
				System.out.println("使用了自己的配置?");
			}
		};
	}
}

当然也可以使用配置版的:
在yml中进行配置

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations:
  - classpath:mybatis/mapper/*.xml

springdata jpa

SpringData是为了简化数据访问的项目,统一数据库标准,包含crud,查询排序分页等操作
具有统一的Repository接口:

  • Repository:统一接口
  • RevisionRepository:基于乐观锁机制
  • CrudRepository:基本CRUD操作
  • PagingAndSortingRepository:基本CRUD和分页

还提供数据访问模板类xxxTemplate
这里访问的是关系型数据库,使用jpa:
JPA:Java持久化层API,JavaEE的规范,JSR317
JPA:基于ORM(Object Relation Mapping):对象关系映射
编写一个实体类和数据表进行映射并配置映射关系
jpa配置:

  jpa:
    hibernate:
    # 更新或创建数据表结构,没有就创建,有就更新
      ddl-auto: update
    # 每次增删改查在控制台显示sql
    show-sql: true

User:

/**
 * @Entity 告诉JPA这是一个实体类(和数据库表进行映射)
 * @Table 告诉和那个表进行映射,而且不存在还会自动创建,如果省略表名则是类名小写
 * @author yxy
 *
 */
@Entity
@Table(name = "tb_user")
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class User {

	/**
	 * 设置为自增主键
	 */
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	@Column(name = "lastName",length = 20)
	private String username;
	//如果省略则默认是就是属性名
	private String email;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String username, String email) {
		super();
		this.id = id;
		this.username = username;
		this.email = email;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", email=" + email + "]";
	}
	
}

测试查询和插入方法:

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/user/{id}")
	public User getUserById(@PathVariable("id")Integer id) {
		return userRepository.getOne(id);
	}
	@GetMapping("/user")
	public User saveUser(User user) {
		userRepository.save(user);
		return user;
	}
}

你可能感兴趣的:(springboot)