spring boot数据访问

2019-06-29  本文已影响0人  topshi

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
     @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<String, String> 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<String, String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

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

@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 {
@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/
public interface EmployeeMapper {
    Employee getEmployeeById(Integer id);
}
<?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接口的类路径->
<mapper namespace="cong.springboot.mapper.EmployeeMapper">
    <!-id是对应的接口方法->
    <select id="getEmployeeById" resultType="cong.springboot.bean.Employee">
        SELECT * FROM employee_tbl WHERE id = #{id}
    </select>
</mapper>
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;
//继承JpaRepository完成对数据库的操作
public interface UserRepository extends JpaRepository<User, Integer>{
}
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/runoob
    
  jpa:
    hibernate:
      ddl-auto: update //如果数据库中不存在该表则创建
    show-sql: true
@RestController
public class UserController {
    @Autowired
    UserRepository userRepository;

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

猜你喜欢

热点阅读