第一步引入依賴java
<!-- 引入starter--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> <scope>runtime</scope> </dependency> <!-- MySQL的JDBC驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 引入第三方數據源 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency>
第二步配置文件mysql
#數據源配置 spring.datasource.url=jdbc:mysql://localhost:3306/hospital_vaccine_manage?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=***** spring.datasource.driver-class-name=com.mysql.jdbc.Driver #druid鏈接池 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #增長打印sql語句,通常用於本地開發測試 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #mybaties配置 mybatis.mapper-locations = classpath:mapper/*Mapper.xml mybatis.type-aliases-package = com.example.pojo
在classPath下新建文件夾 mapper ,用來存放 mapper.xml文件spring
第三步啓動類增長註解掃描 mapper.java ,通常稱爲 dao 層sql
@MapperScan("com.example.dao")
第四步 開發apache
例如 childsMapper.xmlmybatis
<?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.example.dao.ChildsDao" > <resultMap id="BaseResultMap" type="com.example.pojo.Childs" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="pass_word" property="passWord" jdbcType="VARCHAR" /> <result column="birthday" property="birthday" jdbcType="DATE" /> <result column="sex" property="sex" jdbcType="VARCHAR" /> <result column="birth_city" property="birthCity" jdbcType="VARCHAR" /> <result column="real_name" property="realName" jdbcType="VARCHAR" /> <result column="father_name" property="fatherName" jdbcType="VARCHAR" /> <result column="monther_name" property="montherName" jdbcType="VARCHAR" /> <result column="parent_phone" property="parentPhone" jdbcType="VARCHAR" /> <result column="user_role" property="userRole" jdbcType="VARCHAR" /> <result column="enable_flag" property="enableFlag" jdbcType="VARCHAR" /> </resultMap> <select id="findAll" resultMap="BaseResultMap"> select * from childs </select> </mapper>
childsDao.javaapp
@Mapper public interface ChildsDao { List<Childs> findAll(); }
注意 @Mapper spring-boot
從mybatis3.4.0開始加入了@Mapper註解,目的就是爲了避免再寫mapper映射文件,我以爲寫SQL比較靈活測試
childsService.javaui
@Service public class ChildsService { @Autowired private ChildsDao childsDao; public List<Childs> test1(){ List<Childs> childsList=childsDao.findAll(); return childsList; } }
controller 這層不作演示