SpringBoot+PostgreSQL+MyBaties整合

開發(fā)環(huán)境

Windows10+Idea+PostgreSQL

PostgreSQL安裝

可能是電腦環(huán)境問題,遇到不少坑,先是安裝版總是失敗,然后是解壓版總是啟動錯誤
Windows安裝版
Windows解壓版

SpringBoot創(chuàng)建

創(chuàng)建時勾選上MyBaties,PostgreSQL,創(chuàng)建成功后pom.xml文件有如下代碼

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

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

application.yml文件的配置

配置數(shù)據(jù)庫連接配置,MyBaties相關(guān)配置

spring:
  datasource:
    url: jdbc:postgresql://主機地址:端口(一般是5432)/數(shù)據(jù)庫名字
    username: 用戶名
    password:密碼
    driver-class-name: org.postgresql.Driver
mybatis:
  mapper-locations: 映射文件路徑/*.xml
  type-aliases-package: 映射實體類包名

開始整合

首先創(chuàng)建要映射的實體類(此處過程省略)
Dao層創(chuàng)建映射接口

public interface 接口名{
    Integer insertSelective(Person person);//一個插入的例子
}

在配置的映射資源文件路徑下簡歷???.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="映射接口包名.映射接口名">
    <resultMap id="BaseMapper" type="實體類表名.Person">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="name" jdbcType="VARCHAR" property="name"/>
        <result column="addr" jdbcType="VARCHAR" property="addr"/>
    </resultMap>

    <insert id="insertSelective" keyColumn="id" keyProperty="id"
            parameterType="實體類表名.Person" useGeneratedKeys="true">
        insert into springboot(name,addr) values(#{name,jdbcType=VARCHAR},#{addr,jdbcType=VARCHAR})
    </insert>

    <select id="selectAll" resultMap="BaseMapper">
        select * from springboot order by name desc
    </select>
</mapper>

注意:SpringBoot開始的Application要加如下注解
@ComponentScan(value={"@Controller等等注解所在的包名","......"})
@MapperScan("Dao層創(chuàng)建映射接口所在包名")
在其他類中調(diào)用即可

對PostgreSQL的JSON數(shù)據(jù)的操作點擊這里查看
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容