spring boot数据访问

spring boot数据访问之JDBC

首先在全局配置文件中设置连接数据库的一些信息,包括用户名、密码、url、mysql驱动

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/runoob?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
  • spring.datasource.type可以指定数据源的类型,默认情况下是org.apache.tomcat.jdbc.pool.DataSource
  • 数据源相关的配置在DataSourceProperties类中,属性和全局文件前缀为spring.datasource的设置项绑定。
  • spring boot默认支持org.apache.tomcat.jdbc.pool.DataSourcecom.zaxxer.hikari.HikariDataSourceorg.apache.commons.dbcp2.BasicDataSource
  • 自定义数据源
     @Bean
     public DataSource dataSource(DataSourceProperties properties) {
          //使用建造者模式创建数据源,利用反射创建响应type的数据源并且绑定相关属性
            return properties.initializeDataSourceBuilder().build();
        }

spring boot数据访问之Druid

Druid可以说是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池!
在我们上一小节的全局配置文件中使用spring.datasource.type属性指定使用druid数据源。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/runoob?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

在创建自定义数据源时,使用的构造者如下

    public DataSourceBuilder initializeDataSourceBuilder() {
        return DataSourceBuilder.create(this.getClassLoader()).
                type(this.getType()).
                driverClassName(this.determineDriverClassName()).
                url(this.determineUrl()).
                username(this.determineUsername()).
                password(this.determinePassword());
    }

可以看出,只是配置了四个比较基本的属性,如果想设置数据源的一些其它属性则需要自己编写自动配置类。

@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 initParams = new HashMap<>();
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword", "123456");
        initParams.put("allow","");
        bean.setInitParameters(initParams);
        return bean;
    }

    //2.配置一个过滤器bean
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

spring boot数据访问之整合Mybatis(注解版)

  • 编写mapper接口
@Mapper  //mapper必不可少
public interface StudentMapper {
    @Select("select * from student where id = #{id}")
    Student getStudentById(Integer id);

    @Delete("delete from student where id = #{id}")
    int deleteStudentById(Integer id);

    @Insert("insert into student (name, subject, score) values(#{name},#{subject},#{score})")
    int insertStudent(Student stu);

    @Update("update student set name = #{name} where id = #{id}")
    int updateStudent(Student stu);
}

@Mapper注解的话比较麻烦,可以在主配置类使用@MapperScan批量扫描

@MapperScan("cong.springboot.mapper")
@SpringBootApplication
public class SpringbootMybatisApplication {
  • 在controller中使用mapper代理对象进行数据库访问
@RestController
public class StudentController {
    @Autowired
    StudentMapper studentMapper;

    @GetMapping("/stu/{id}")
    public Student getStudent(@PathVariable("id") Integer id){
        return studentMapper.getStudentById(id);
    }

    @GetMapping("/stu")
    public Student insertStudent(Student stu){
        studentMapper.insertStudent(stu);
        return stu;
    }
}

如果要修改mybatis的一些配置可以写一个配置类,向容器中加入ConfigurationCustomizer组件,改变mybatis的配置规则。(也可在全局配置文件中配置)

@org.springframework.context.annotation.Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                //开启驼峰命名
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

spring boot数据访问之整合Mybatis(配置版)

配置版需要增加两个xml配置文件:

  1. mybatis-config.xml: 将其放在resource/mybatis/
  2. xxxmapper.xml:将其放在resource/mybatis/mapper/
  • 首先,常规操作,写好mapper接口
public interface EmployeeMapper {
    Employee getEmployeeById(Integer id);
}
  • mybatis-config.xml基本不用配置,数据源等配置已在application.yml中配置。只需要配置mapper.xml文件




    
    

  • 在application.xml中指定mybatis全局配置文件和mapper.xml的位置
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

spring boot数据访问之整合JPA

  • 首先编写一个实体类和数据表进行映射,并且配置好映射关系
//使用JPA注解配置映射关系
@Entity   //告诉JPA这是一个实体类,和数据表映射
@Table(name = "tbl_user")
public class User {

    @Id//这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;
    @Column(name = "name",length = 50) //这是和数据表对应的一个列
    private String name;
    @Column //默认列名是属性名
    private String email;
  • 编写一个Dao接口来操作实体类对应的数据表
//继承JpaRepository完成对数据库的操作
public interface UserRepository extends JpaRepository{
}
  • 基本的配置
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/runoob
    
  jpa:
    hibernate:
      ddl-auto: update //如果数据库中不存在该表则创建
    show-sql: true
  • 编写Controller做测试
@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        Optional users = userRepository.findById(id);
        return users.get();
    }
    @RequestMapping("/user")
    public User insertUser(User user){
        User save = userRepository.save(user);
        return save;
    }
}

你可能感兴趣的:(spring boot数据访问)