1、下载安装一个Mysql数据库及管理工具,同类工具很多,随便找一个都可以,我在windows下做测试项目习惯使用的是haosql
它内部集成了MySql-Front管理工具
2、创建一个j_user表,有如下列,先设计几个常用列,以后有需要再扩展字段
3、打开mybatis官网可以查看资料
http://www.mybatis.org/mybatis-3/zh/getting-started.html
pom.xml中添加mybatis和mysql
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> </dependency>
4、安装一个插件,可以自动生成setter,getter
引入依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
5、添加一个数据库连接,
本地mysql版本5.7,使用高版本驱动提示时区错误,改为MySql For 5.1
或者链接字符串增加?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
6、添加一个插件
7、连接数据库生成代码
8、结构如下
修改JUserDao.xml
或者修改生成配置,从新生成也行
9、application.properties修改如下
spring.datasource.url = jdbc:mysql://localhost:3306/jgdb
spring.datasource.username = root
spring.datasource.password = ***
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.typeAliasesPackage=com.jgui.mapper
10、修改pom.xml,build下确保有如下代码
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
11、JUserDao下增加@Mapper
12、启动文件增加MappScan,上一步和此处任做一个即可。
package com.jgui; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @MapperScan({ "com.jgui.dao"}) @SpringBootApplication public class JgadminApplication { public static void main(String[] args) { SpringApplication.run(JgadminApplication.class, args); } }
13、为了简单测试,不再建立Services层,直接修改HelloController如下
@RestController public class HelloController { @Resource private JUserDao userDao; @RequestMapping("/Hello") public String hello() { return userDao.selectByPrimaryKey(1).getUsername(); //return "Hello World11"; } }
14、在浏览器访问
15、经验教训
Invalid bound statement (not found)
No qualifying bean of type 'com.jgui.dao.JUserDao' available
8-12不能遗漏,不然会报上面两个错误!
该项目GITHub的地址:https://github.com/zhaogaojian/jadmin