【SpringBoot】整合 - JDBC、Mybatis、JPA

10.1 整合JDBC

image-20200711144521150 image-20200711144631692 image-20200711145437652 image-20200711145524279 image-20200711145637766 image-20200711150414800 image-20200711150557902 image-20200711150651507 image-20200711151111662

10.2 整合Mybatis

 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
image-20200718194603081 image-20200718194104274
<!--      druid  数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

druid 数据源配置,在主配置文件yml文件中编写如下配置

spring:
  datasource:
#   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.40.132:3306/db01
    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

# 使用xml文件配置时使用下面的配置映射到mybatis的配置文件位置
mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

# 会自动加载该路径下得sql
#    schema:
#      - classpath:sql/department.sql
#      - classpath:sql/employee.sql

编写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;
    }
}

注解版

加入domain类

编写dao层

@Mapper
public interface BookDao {

    @Select("select * from tb_book")
    public List<Book> findAll();

    @Select("select * from tb_book where id=#{id}")
    public Book findById(int id);

    @Options(useGeneratedKeys = true,keyProperty = "id")//主键自增长
    @Insert("insert into tb_book(id,name)values(#{id},#{name})")
    public void insert(Book book);

    @Delete("delete from tb_book where id=#{id} and name=#{name}")
    public void delete(Book book);

    @Update("update tb_book set name=#{name} where id=#{id}")
    public void update(Book book);

}

编写service层,此处省略,自行添加

编写controller层

@RestController
public class BookController {
    @Autowired
    BookService bookService;


    @GetMapping("/book/{id}")
    public Book findById(@PathVariable("id") int id){
        return bookService.findById(1);
    }
    @GetMapping("/book")
    public Book insert(Book book){
        bookService.insert(book);
        return book;
    }

//    @GetMapping("/book")
//    public void delete(Book book){
//        bookService.delete(book);
//    }
}

启动服务器

image-20200718204622889 image-20200718204753541 image-20200718211709270 image-20200718212728971

踩坑

如果启动程序时有如下报错,说明缺少log4j,导入依赖即可

image-20200718204223220
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>

导入依赖后还出现警告,那就自己手动在resources目录下创建一个 log4j。properties文件

image-20200718212906894
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

xml版

mybatis-3的官方文档,找到全局配置文件:https://mybatis.org/mybatis-3/getting-started.html

由于数据库的驱动链接等配置信息在yml主配置文件中都写完了,这里的配置就不用加了

<?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>
image-20200718215510408

设置一个全局配置文件,和一个mapper映射配置文件

image-20200718221751485

编写dao层接口,和对应接口的mapper映射配置文件

//@Mapper 或者 @MapperScan 将接口扫描并装配到容器中
public interface StudentDao {

    public Student findById(Integer id);

    public void  insert(Student student);

}
<?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="zy.code.springboot06mybatis.dao.StudentDao">
    <select id="findById" parameterType="int" resultType="zy.code.springboot06mybatis.domain.Student">
    select * from student where id = #{id}
  </select>

    <insert id="insert" parameterType="zy.code.springboot06mybatis.domain.Student">
        insert into student(id,name) values (#{id},#{name})
    </insert>
</mapper>

编写测试controller层,直接调用dao层,测试是否能够操作数据库成功

@RestController
public class StudentController {

    @Autowired
    StudentDao studentDao;

    @GetMapping("/stu/{id}")
    public Student findById(@PathVariable("id") Integer id){
        Student stu = studentDao.findById(id);
        return stu;
    }
    @GetMapping("/stu")
    public Student insert(Student student){
        studentDao.insert(student);
        return student;
    }

}

image-20200718222154533

10.3 整合SpringData-JPA

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页