Spring boot 与 mybatis 结合

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot 致力于在蓬勃发展的快速应用开发领域 (rapid application development) 成为领导者。

特点

创建独立的 Spring 应用程序

嵌入的 Tomcat,无需部署 WAR 文件

简化 Maven 配置

自动配置 Spring

提供生产就绪型功能,如指标,健康检查和外部配置

绝对没有代码生成并且对 XML 也没有配置要求

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs (Plain Ordinary Java Object, 普通的 Java 对象) 映射成数据库中的记录。

先看一下项目结构:

 

项目所需要的依赖:

<dependencies>

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>

<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-configuration-processor </artifactId>
<optional> true </optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>

</dependencies>

Mybatis 配置文件:

<?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="useGeneratedKeys" value="true"/>
    <!-- 允许使用自定义列名 -->
    <setting name="useColumnLabel" value="true"/>
    <!-- 开启驼峰命名,数据库到实体类的映射 create_table->createTable-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
</configuration>

实体类 artileStudy 的代码,我这里就省略封装了:

@Entity
public class articleStudy {
  @Id
  @GeneratedValue (strategy = GenerationType.IDENTITY)
  private int studyId;
  private String title;
  private String content;
  private String tag;
  private String date;
private String description;
}

需要注意的是,如果你数据库中列名是 study_id,那么在实体类中就得命名成 studyId,这就是驼峰命名。不然会出现 bug:Mybatis 查询数据库 id 都是 0

Dao 代码:

public interface Article_Study_Dao {
  List<articleStudy> queryArticle ();
  List<articleStudy> queryArticleById (int id);
  int insertArticle (articleStudy article_study);
  int updateArticle (articleStudy article_study);
  int deleteArticle (int id);
}

在 dao 中类要写成接口形式的,然后再 mybatis 的 mapper 文件中实现。

Mapper 配置文件:Article_Study_Dao 代码

<?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.tzs.blog.dao.Article_Study_Dao">

  <select id="queryArticle" resultType="com.tzs.blog.entity.articleStudy">
        SELECT * FROM article_study
  </select>

  <select id="queryArticleById" resultType="com.tzs.blog.entity.articleStudy">
        SELECT * FROM article_study where study_id=#{id}
  </select>

  <update id="updateArticle">
    update article_study
    <set>
      <if test="title != null">title=#{title},</if>
      <if test="tag != null">tag=#{tag},</if>
      <if test="date != null">date=#{date},</if>
      <if test="content != null">content=#{content},</if>
      <if test="description != null">description=#{description}</if>
    </set>
    where study_id=#{studyId}
  </update>
  <insert id="insertArticle" parameterType="com.tzs.blog.entity.articleStudy">
        insert into article_study (date,content,tag,description,title)
        values (#{date},#{content},#{tag},#{description},#{title})
  </insert>

  <delete id="deleteArticle">
    DELETE FROM article_study WHERE study_id = #{id}
  </delete>
</mapper>

Mapper 中的 namespace 是你的 dao 所在路径,增删改查中绑定的 id 是你 dao 接口中的方法名, parameterType 是你传进去的参数类型, resultType 是返回的数据类型。

当 dao 中方法的参数是一个实体类时,在 mapper 中给字段赋值,不需要写成 title = #{ article_study.title } 的形式,直接写 title = #{ title } 就可以了

然后是 application-dev.yml 中数据库和 mybatis 的一些基本配置:

jdbc.driver: com.mysql.cj.jdbc.Driver
jdbc.url: jdbc:mysql://localhost:3306/article?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username : root
jdbc.password : 123456

#mybatis
mybatis_config_file: mybatis-config.xml
mapper_path: /mapper/**.xml
entity_package: com.tzs.blog.entity

在这个项目中我是使用的 java 类就行配置的,接下来就是 DataSourceConfiguration 数据库配置类代码:

@Configuration
// 配置 mybatis mapper 的扫描路径
@MapperScan ("com.tzs.blog.dao")
public class DataSourceConfiguration {
  @Value ("${jdbc.driver}")
  private String jdbcDriver;
  @Value ("${jdbc.url}")
  private String url;
  @Value ("${jdbc.username}")
  private String username;
  @Value ("${jdbc.password}")
  private String password;

  @Bean (name = "dataSource")
  public ComboPooledDataSource createDataSource () throws PropertyVetoException {
    ComboPooledDataSource dataSource =new ComboPooledDataSource ();
    dataSource.setDriverClass (jdbcDriver);
    dataSource.setJdbcUrl (url);
    dataSource.setUser (username);
    dataSource.setPassword (password);
    // 关闭连接后不自动 commit
    dataSource.setAutoCommitOnClose (false);
    return dataSource;
  }
}

然后是 sessionFactory 配置类,需要把数据库和 mybatis 注入进去:

@Configuration
public class SessionFactoryConfiguration {
  //mybatis-config.xml 配置文件路径
  @Value ("${mybatis_config_file}")
  private String mybatisConfigFilePath;

  @Resource
  private DataSource dataSource;

  @Value ("${mapper_path}")
  private String mapperPath;

  @Value ("${entity_package}")
  private String entityPackage;


  @Bean (name = "sqlSessionFactory")
  public SqlSessionFactoryBean createSessionFactoryBean () throws IOException {
    SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean ();
    sqlSessionFactoryBean.setConfigLocation (new ClassPathResource (mybatisConfigFilePath));
    PathMatchingResourcePatternResolver resolver=new PathMatchingResourcePatternResolver ();
    String packageSearchPath=PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
    sqlSessionFactoryBean.setMapperLocations (resolver.getResources (packageSearchPath));
    sqlSessionFactoryBean.setDataSource (dataSource);
    sqlSessionFactoryBean.setTypeAliasesPackage (entityPackage);
    return sqlSessionFactoryBean;
  }
}

因为这个项目是用来举例,所以就没有写业务类代码,直接就是控制层代码了:

@RestController
public class Article_StudyController {

  @Resource
  private Article_Study_Dao article_study_dao;

  @GetMapping ("/getStudy")
  public List<articleStudy> getStudy () {
    List<articleStudy> list = article_study_dao.queryArticle ();
    return list;
  }

  @GetMapping ("/getStudyById/{id}")
  public List<articleStudy> getStudyById (@PathVariable (value = "id") int id) {
    List<articleStudy> list = article_study_dao.queryArticleById (id);
    return list;
  }

  @GetMapping ("/deleteStudyById/{id}")
  public String deleteStudyById (@PathVariable (value = "id") int id) {
    int count = article_study_dao.deleteArticle (id);
    if (count > 0) {
      return "success";
    }
    return "error";
  }

  @PostMapping ("/insertStudy")
  public String insertStudy (articleStudy articleStudy) {
    int count = article_study_dao.insertArticle (articleStudy);
    if (count > 0) {
      return "success";
    }
    return "error";
  }

  @PutMapping ("/updateStudy")
  public String updateStudy (articleStudy articleStudy) {
    int count = article_study_dao.updateArticle (articleStudy);

    if (count > 0) {
      return "success";
    }
    return "error";
  }
}

SpringBoot 提供的获取参数注解包括:@PathVariable,@RequestParam,@RequestBody, 三者的区别如下表:

 

请求示例:

@PathVariable:/getStudy/{id}
@RequestParam: /getStudy?id=1 (url 方式)
@RequestBody : {“name”: “zhangsan”, “id”: “1” }

获取示例:

@GetMapping ("/getStudyById/{id}")
  public List<articleStudy> getStudyById (@PathVariable (value = "id") int id) {
    List<articleStudy> list = article_study_dao.queryArticleById (id);
    return list;
}

@GetMapping ("/getStudyById")
  public List<articleStudy> getStudyById (@RequestParam (value = "id") int id) {
    List<articleStudy> list = article_study_dao.queryArticleById (id);
    return list;
}

// @RequestBody 可以直接对应实体类
@PostMapping ("/getStudyById")
  public String getStudyById (@RequestBody articleStudy as) {
    return as.getContent+”,”+as.getTitle;
}

使用 From-data,x-www.form-urlencoded 传参,可以直接对应实体类。

请求:/updateStudy data:{ content:”abc” ,title: “传参”}

获取:

@PutMapping ("/updateStudy")
  public String updateStudy (articleStudy articleStudy) {
   return articleStudy.getContent ();
}

这样,springboot 和 mybatis 结合就完成了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值