開發(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)用即可