第一章:注解版
-
导入配置:
<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