第一章:注解版
-
導入配置:
<groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version> </dependency>
- 步驟:
- 配置數據源見 Druid 配置
- 創建表
- 創建實體類:
public class Txperson {public class TxPerson {private int pid;private String pname;private String addr;private int gender;private Date birth;} }
- 創建 Mapper 層:
@Mapper public interface TxPersonMapper {@Select("select * from tx_person")public List<TxPerson> getPersons();@Select("select * from tx_person t where t.pid = #{id}")public TxPerson getPersonById(int id);@Options(useGeneratedKeys =true, keyProperty = "pid")@Insert("insert into tx_person(pid, pname, addr,gender, birth)" +" values(#{pid}, #{pname}, #{addr},#{gender}, #{birth})")public void insert(TxPerson person);@Delete("delete from tx_person where pid = #{id}")public void update(int id);}
- 編寫配置類解決駝峰模式和數據庫中下劃線不能映射的問題
@Configuration public class MybatisConfig {@Beanpublic ConfigurationCustomizer getCustomizer(){return new ConfigurationCustomizer() {@Overridepublic void customize(org.apache.ibatis.session.Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);}};} }
- 進行測試:
第二章:SpringBoot 整合 MyBatis 配置文件
-
創建 sqlMapConfig.xml 配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration></configuration>
- 映射文件 PersonMapper.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="cn.tx.mapper.TxPersonMapper"><select id="getPersons" resultType="TxPerson">select * from tx_person</select> </mapper>
- 在 application.yaml 中配置 mybatis 的信息
mybatis:config-location: classpath:mybatis/sqlMapConfig.xmlmapper-locations: classpath:mybatis/mapper/*.xmltype-aliases-package: cn.tx.springboot.jdbc_demo1