新建springBoot项目
创建目录结构
导入数据库
1.Navicat Premium里新建 home-lib 数据库
2.选择项目文档中home-lib.sql文件
3.Navicat Premium打开前面新建的数据库,右键点击运行sql文件
导入需要的包
pom.xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lib</groupId>
<artifactId>home-lib</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>home-lib</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<mybatis.generator.version>1.3.2</mybatis.generator.version>
<mysql.connector.java.version>6.0.6</mysql.connector.java.version>
<!-- Used by MyBatis Generator to Generate Codes -->
<!-- 运行命令: mvn mybatis-generator:generate -e -->
<!--<classPathEntry.mysql.location>${basedir}/target/${project.artifactId}/WEB-INF/lib/mysql-connector-java-${mysql.connector.java.version}.jar</classPathEntry.mysql.location>-->
<classPathEntry.mysql.location>/Users/14217/Downloads/mysql-connector-java-5.1.38.jar</classPathEntry.mysql.location>
<javaModelGenerator.targetProject>${basedir}/src/main/java</javaModelGenerator.targetProject>
<sqlMapGenerator.targetProject>${basedir}/src/main/resources</sqlMapGenerator.targetProject>
<javaClientGenerator.targetProject>${basedir}/src/main/java</javaClientGenerator.targetProject>
<mybatis.generator.configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</mybatis.generator.configurationFile>
<mybatis.generator.overwrite>true</mybatis.generator.overwrite>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- 自动生成代码 mybatis-generator -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator</artifactId>
<version>1.3.5</version>
<type>pom</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!--避坑包-->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!--解析html包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--mybatis 自动生成插件-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!-- 热部署设置 optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- http://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<!--lombok 用注解代替set Git方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
</configuration>
</plugin>
<!-- (1) mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
<!-- (2) mybatis generator 自动生成代码插件 -->
<!-- <plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>-->
</plugins>
</build>
</project>
配置自动生成代码
1.generator目录下
新建 generatorConfig.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="C:\Users\P0114255\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/cat" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.lib.homelib.model" targetProject="${javaClientGenerator.targetProject}">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="mapping" targetProject="${sqlMapGenerator.targetProject}">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.lib.homelib.mapper" targetProject="${javaClientGenerator.targetProject}">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="t_user" domainObjectName="TUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
其中<classPathEntry location="C:\Users\P0114255\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar" />
location对应的地址可以直接从maven里复制
2.用maven project编译
输入:mybatis-generator:generate -e
成功后,在这三个目录下生成三个文件,如果失败的话,检查下generatorConfig.xml里面的目录结构
controller的几种调用方法
1.新建LoginController
package com.lib.homelib.controller;
import com.lib.homelib.mapper.DictMapper;
import com.lib.homelib.model.Dict;
import com.lib.homelib.service.DictService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@RequestMapping("/Login")
@Controller
public class LoginController {
@Resource
public DictMapper dictMapper;
@Resource
DictService dictService;
/**
* 直接使用Mapper
* @return
*/
@RequestMapping(value = "/index", produces = "text/html")
public String routerListView() {
Dict dict = dictMapper.selectByPrimaryKey(Long.valueOf(1));
System.out.println(dict.getId());
return "index";
}
/**
* 直接使用Mapper
* @return
*/
@RequestMapping(value = "/getAllUser")
@ResponseBody
public Map<String,Object> getAllUser() {
Map<String,Object> resutl = new HashMap<>();
resutl.put("code","100");
resutl.put("user",dictMapper.findAllUser());
return resutl;
}
/**
* Service中用Mapper
* @return
*/
@RequestMapping("/getAllUserService")
@ResponseBody
public Map<String,Object> getAllUserService(){
Map<String,Object> resutl = new HashMap<>();
resutl.put("code","100");
resutl.put("user",dictService.findAllUser());
return resutl;
}
/**
* Service中调用Dao方法,dao通过构造方法注入
* @return
*/
@RequestMapping("/getAllUserServiceDao")
@ResponseBody
public Map<String,Object> getAllUserServiceDao(){
Map<String,Object> resutl = new HashMap<>();
resutl.put("code","100");
resutl.put("user",dictService.findAllUserDao());
return resutl;
}
}
2.service包中新建DictService文件
package com.lib.homelib.service;
import com.lib.homelib.model.Dict;
import java.util.List;
public interface DictService {
Dict findUserById(Long id);
List<Dict> findAllUser();
List<Dict> findAllUserDao();
}
3.service包中新建Impl包,Impl包中创建DictServiceImpl文件
package com.lib.homelib.service.imp;
import com.lib.homelib.dao.DictDao;
import com.lib.homelib.mapper.DictMapper;
import com.lib.homelib.model.Dict;
import com.lib.homelib.service.DictService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class DictServiceImpl implements DictService {
@Resource
DictMapper dictMapper;
@Resource
DictDao dictDao;
@Override
public Dict findUserById(Long id) {
Dict dict = new Dict();
try {
dict = dictMapper.selectByPrimaryKey(id);
}catch (Exception e){
e.printStackTrace();
}
return dict;
}
@Override
public List<Dict> findAllUser() {
List<Dict> userList = dictMapper.findAllUser();
System.out.println("数组长度为:"+userList.size());
return userList;
}
@Override
public List<Dict> findAllUserDao() {
List<Dict> userList = dictMapper.findAllUser();
System.out.println("数组长度为:"+userList.size());
return userList;
}
}
4.dao包中创建DictDao文件
package com.lib.homelib.dao;
import com.lib.homelib.model.Dict;
import java.util.List;
public interface DictDao {
List<Dict> findAllUser();
}
5.dao包中创建Impl包,包中创建DictDaoImpl文件
package com.lib.homelib.dao.imp;
import com.lib.homelib.dao.DictDao;
import com.lib.homelib.model.Dict;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class DictDaoImpl implements DictDao {
@Autowired
private SqlSessionTemplate mySessionTemplate;
//在这里用构造方法注入
public DictDaoImpl(SqlSessionTemplate sqlSessionTemplate){
this.mySessionTemplate = sqlSessionTemplate;
}
@Override
public List<Dict> findAllUser() {
return mySessionTemplate.selectList("Dict.findAllUser");
}
}
6.resources目录下的mapping目录中,加入新的方法
<select id="findAllUser" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from dict
</select>
加完后的内容为
<?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.bootmy.mapper.DictMapper">
<resultMap id="BaseResultMap" type="com.bootmy.model.Dict">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="dict_name" jdbcType="VARCHAR" property="dictName" />
<result column="dict_key" jdbcType="VARCHAR" property="dictKey" />
<result column="dict_code" jdbcType="VARCHAR" property="dictCode" />
<result column="dict_delete_directly" jdbcType="INTEGER" property="dictDeleteDirectly" />
<result column="dict_note" jdbcType="VARCHAR" property="dictNote" />
<result column="dict_status" jdbcType="INTEGER" property="dictStatus" />
</resultMap>
<sql id="Base_Column_List">
id, dict_name, dict_key, dict_code, dict_delete_directly, dict_note, dict_status
</sql>
<select id="findAllUser" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from dict
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from dict
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from dict
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.bootmy.model.Dict">
insert into dict (id, dict_name, dict_key,
dict_code, dict_delete_directly, dict_note,
dict_status)
values (#{id,jdbcType=BIGINT}, #{dictName,jdbcType=VARCHAR}, #{dictKey,jdbcType=VARCHAR},
#{dictCode,jdbcType=VARCHAR}, #{dictDeleteDirectly,jdbcType=INTEGER}, #{dictNote,jdbcType=VARCHAR},
#{dictStatus,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.bootmy.model.Dict">
insert into dict
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="dictName != null">
dict_name,
</if>
<if test="dictKey != null">
dict_key,
</if>
<if test="dictCode != null">
dict_code,
</if>
<if test="dictDeleteDirectly != null">
dict_delete_directly,
</if>
<if test="dictNote != null">
dict_note,
</if>
<if test="dictStatus != null">
dict_status,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="dictName != null">
#{dictName,jdbcType=VARCHAR},
</if>
<if test="dictKey != null">
#{dictKey,jdbcType=VARCHAR},
</if>
<if test="dictCode != null">
#{dictCode,jdbcType=VARCHAR},
</if>
<if test="dictDeleteDirectly != null">
#{dictDeleteDirectly,jdbcType=INTEGER},
</if>
<if test="dictNote != null">
#{dictNote,jdbcType=VARCHAR},
</if>
<if test="dictStatus != null">
#{dictStatus,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.bootmy.model.Dict">
update dict
<set>
<if test="dictName != null">
dict_name = #{dictName,jdbcType=VARCHAR},
</if>
<if test="dictKey != null">
dict_key = #{dictKey,jdbcType=VARCHAR},
</if>
<if test="dictCode != null">
dict_code = #{dictCode,jdbcType=VARCHAR},
</if>
<if test="dictDeleteDirectly != null">
dict_delete_directly = #{dictDeleteDirectly,jdbcType=INTEGER},
</if>
<if test="dictNote != null">
dict_note = #{dictNote,jdbcType=VARCHAR},
</if>
<if test="dictStatus != null">
dict_status = #{dictStatus,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.bootmy.model.Dict">
update dict
set dict_name = #{dictName,jdbcType=VARCHAR},
dict_key = #{dictKey,jdbcType=VARCHAR},
dict_code = #{dictCode,jdbcType=VARCHAR},
dict_delete_directly = #{dictDeleteDirectly,jdbcType=INTEGER},
dict_note = #{dictNote,jdbcType=VARCHAR},
dict_status = #{dictStatus,jdbcType=INTEGER}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
7.mapper包下存在的DictMapper里加入自对应的List<Dict> findAllUser();方法
8.springboot启动类SpringBootMybatisApplication 中加注解
@MapperScan(value = "com.bootmy.mapper")
@ComponentScan(basePackages = "com.bootmy")
SpringBootMybatisApplication中内容为
package com.lib.homelib;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@MapperScan(value = "com.lib.homelib.mapper")
@ComponentScan(basePackages = "com.lib.homelib")
@EnableSwagger2
public class HomeLibApplication {
public static void main(String[] args) {
SpringApplication.run(HomeLibApplication.class, args);
}
}
9.配置文件application.properties中内容
server.port=<span class="hljs-number">8080</span>
<span class="hljs-comment">#设定ftl文件路径</span>
spring.freemarker.template-loader-path=classpath:<span class="hljs-regexp">/templates
spring.freemarker.cache=false
spring.freemarker.suffix=.html
#设定静态文件路径,js,css等
#spring.mvc.static-path-pattern=/static</span><span class="hljs-regexp">/**
#热部署生效
spring.devtools.restart.enabled:true
#设置重启的目录
spring.devtools.restart.additional-paths:src/main</span><span class="hljs-regexp">/java
#classpath目录下的WEB-INF文件夹内容修改不重启
spring.devtools.restart.exclude:WEB-INF/</span>**
<span class="hljs-comment">#端口后加</span>
<span class="hljs-comment">#server.servlet.context-path=/caisexiaochou</span>
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:<span class="hljs-regexp">//</span><span class="hljs-number">127.0</span>.<span class="hljs-number">0</span>.<span class="hljs-number">1</span>:<span class="hljs-number">3306</span>/cat?characterEncoding=UTF-<span class="hljs-number">8</span>&useUnicode=true
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.minIdle=<span class="hljs-number">3</span>
spring.datasource.maxWait=<span class="hljs-number">600000</span>
spring.datasource.removeAbandoned=true
spring.datasource.removeAbandonedTimeout=<span class="hljs-number">180</span>
spring.datasource.timeBetweenEvictionRunsMillis=<span class="hljs-number">600000</span>
spring.datasource.minEvictableIdleTimeMillis=<span class="hljs-number">300000</span>
spring.datasource.validationQuery=SELECT <span class="hljs-number">1</span> FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=<span class="hljs-number">50</span>
spring.datasource.filters=<span class="hljs-keyword">stat</span>
mybatis.mapper-locations=classpath*:mapping/*Mapper.xml
<span class="hljs-comment">#mybatis.type-aliases-package=com.bootMy.model.*</span>
<span class="hljs-comment">#日志显示SQL</span>
logging.level.com.lib.homelib.mapper = debug
关于热部署的,可以看我另外一篇博客
https://blog.csdn.net/tangcv/article/details/80480542
如果IDEA中设置过的,这里不需要做别的配置,可以直接用,修改完java文件,发现不能重启项目的,可以百度下IDEA设置热部署
10.resources下templates目录下新建 index.html
启动 SpringBootMybatisApplication文件
访问 http://127.0.0.1:8080/Login/index 显示下面内容,成功!
控制台打印
通过dictMapper中生成的方法,传入id 查询对应的一条数据
访问 http://127.0.0.1:8080/Login/getAllUserServiceDao 显示