SpringBoot-9:SpringBoot与数据访问_JDBC_Druid_MyBatis_JPA

一、SpringBoot整合基本JDBC

1、查看SpringBoot的默认数据源

1、在配置文件application.yml中配置数据源

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.22:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver

2、测试类

@RunWith(SpringRunner.class)
@SpringBootTest
class Springboot05DataJdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

效果:

  • 默认使用com.zaxxer.hikari.HikariDataSource作为数据源;
  • 数据源的相关配置都在DataSourceProperties里面;

2、自动建表

  1. spring.datasource下有两个属性 schme、data,其中schema为表初始化语句,data为数据初始化,默认加载schema.sql与data.sql。脚本位置可以通过spring.datasource.schema 与spring.datasource.data 来改变

  2. 在application.yml中通过spring.datasource.schema指定建表脚本的位置:
    在这里插入图片描述
    在SpringBoot1.x中, 运行建表脚本不需要配置便可之间运行,但是在SpringBoot2.x中,我们需要在配置文件中配置一下:initialization-mode: always

	spring:
	  datasource:
	    username: root
	    password: root
	    url: jdbc:mysql://192.168.157.129:3306/jdbc
	    driver-class-name: com.mysql.cj.jdbc.Driver
	    initialization-mode: always
	    # 配置自动建表脚本的位置
	    schema:
	      - classpath:department.sql
  1. 运行启动类之后会自动创建department这个表

3、使用JdbcTemplate查表

使用JdbcTemplate查询表中的数据:
在这里插入图片描述

@Controller
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/query")
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
        return list.get(0);
    }
}

说明:在运行主类后,会自动创建department这个表,然后在表中填入数据并保存,但是建完表以后就要将配置文件的指定建表sql脚本的配置给删除,否则再次启动主类,仍会建表,那么保存的数据就没了

#    schema:
#      - classpath:department.sql

在这里插入图片描述

二、SpringBoot整合Druid数据源

1. 引入Druid数据源的依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>

2. 在配置文件中切换数据源并配置与数据源相关的属性

	spring:
	  datasource:
	    username: root
	    password: root
	    url: jdbc:mysql://192.168.157.129:3306/jdbc
	    driver-class-name: com.mysql.cj.jdbc.Driver
	    # 启动初始化
	    initialization-mode: always
	    # 切换数据源的类型
	    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

3. 编写配置类

	@Configuration
	public class DruidConfig {
	
	    //指定加载appliction.yml文件里面的spring.datasource开头的
	    // DruidDataSource类里面的属性与appliction.yml文件里面的spring.datasource开头的对应映射
	    @ConfigurationProperties(prefix = "spring.datasource")
	    @Bean
	    public DataSource druid(){
	        return  new DruidDataSource();
	    }
	}

4. 以debug方式测试配置的数据源属性是否成功

在这里插入图片描述
注意:在运行测试类的时候报错java.lang.NoClassDefFoundError: org/apache/log4j/Priority,需要在pom.xml中导入依赖:

	<dependency>
	   <groupId>log4j</groupId>
	   <artifactId>log4j</artifactId>
	   <version>1.2.17</version>
	</dependency>

5. 配置Druid的监控

@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","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @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;
    }
}

在这里插入图片描述

三、SpringBoot整合MyBatis

1. 配置Druid数据源

导入依赖:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>

配置数据源相关属性:

spring:
  datasource:
  # 数据源的基本配置DruidConfig
    username: root
    password: root
    url: jdbc:mysql://192.168.157.129:3306/mybatis
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 启动初始化
    initialization-mode: always
    # 切换数据源的类型
    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

创建数据库mybatis:
在这里插入图片描述
编写数据源配置类

@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","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @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;
    }
}

2. 配置启动时初始化的建表脚本

    # 启动时初始化的建表语句
    schema:
      # 一定要注意classpath:后面没有空格
      - classpath:sql/department.sql
      - classpath:sql/employee.sql

    # 启动初始化
    initialization-mode: always

在这里插入图片描述
运行启动类创建数据表,创建完成后就要将上面的配置删掉,以防启动时再次创建。

3. 创建JavaBean封装表的属性

@Data
public class Employee {
    private Integer id;
    private  String lastName;
    private Integer gender;
    private String email;
    private Integer dId;
}
@Data
public class Department {
    private Integer id;
    private String departmentName;
}

4. MyBatis注解版

@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);

    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

Controller层:

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

	//只要传递的参数和类名一致就会自动封装
    @GetMapping("/dept")
    public Department insertDepartment(Department department){
        departmentMapper.insertDept(department);
        return department;
    }

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }
}

在这里插入图片描述
在这里插入图片描述
可以看到在插入数据时,id=null,但查询出来并不为null,可以开启主键自增功能:

 @Options(useGeneratedKeys = true,keyProperty = "id")
 @Insert("insert into department(departmentName) values(#{departmentName})")
 public int insertDept(Department department);

在这里插入图片描述

5. 配置文件版

1、在主类上加上一个注解,用于扫描映射文件的接口的包

@MapperScan("com.hh.springboot.mapper")
@SpringBootApplication
public class Springboot05DataMybatis0Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot05DataMybatis0Application.class, args);
    }
}

2、EmployeeMapper接口:

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

3、EmployeeMapper.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="com.hh.springboot.mapper.EmployeeMapper">

    <select id="getEmpById" resultType="com.hh.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

4、全局配置文件:

<?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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

5、Controller层:

@RestController
public class DeptController {
    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return employeeMapper.getEmpById(id);
    }
}

6、在配置文件中配置位置:

mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

在这里插入图片描述

四、SpringBoot整合JPA

1、application.properties

###############数据源配置################

#配置数据源
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.157.130/jpa?characterEncoding=utf-8&useSSL=false

###############JPA配置######################

#更新或者创建数据库表结构
spring.jpa.hibernate.ddl-auto=update
#控制台显示SQl
spring.jpa.show-sql=true

2、UserRepository

//完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {

}

3、User
@Entity说明这个class是实体类,并且使用默认的orm规则,即class名即数据库表中表名,class字段名即表中的字段名
如果想改变这种默认的orm规则,就要使用@Table来改变class名与数据库中表名的映射规则,@Column来改变class中字段名与db中表的字段名的映射规则

[@Entity]  
   必须与@Id注解 结合使用  
     否则  No identifier specified for entity:   
   name 属性  
    (可选)实体名称。 缺省为实体类的非限定名称。   
        该名称用于引用查询中的实体。  
        该名称不能是Java持久性查询语言中的保留字面值。  
   
   不与@Table结合的话 表名 默认为 SnakeCaseStrategy(命名策略 )为表名  
    若使用 name属性 且没有与@Table结合 则表名为 name值的SnakeCaseStrategy(命名策略 )  
    例如:  
        @Entity  
            public class UserEntity{...} 表名 user_entity  
        @Entity(name="UE")  
            public class UserEntity{...} 表名 ue  
        @Entity(name="UsEntity")  
            public class UserEntity{...} 表名 us_entity  

@Entity//告诉JPA这是一个实体类(和数据库表映射的类)
@Table//指定和那个数据库表对应,如果省略就是类名小写
@Data
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User implements Serializable {
    @Id//表明这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//这是一个自增主键
    private Integer id;
    @Column//这是和数据库表对应的一个列
    private String lastName;
    @Column//省略列名就是属性名
    private String email;
}

4、UserController

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id")Integer id){
        User user = userRepository.getOne(id);
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user){
        User save = userRepository.save(user);
        return save;
    }

}

在这里插入图片描述

发布了665 篇原创文章 · 获赞 115 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/104618334