添加durid,pageHelper依赖, pom.xml如下:
4.0.0
com.wx
wlcx
0.0.1-SNAPSHOT
jar
wlcx
Demo project for wlcx
org.springframework.boot
spring-boot-starter-parent
2.1.0.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1
org.springframework.boot
spring-boot-starter-thymeleaf
2.0.4.RELEASE
com.microsoft.sqlserver
mssql-jdbc
runtime
org.springframework.boot
spring-boot-starter-test
test
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3
com.alibaba
druid
1.1.8
log4j
log4j
1.2.16
compile
org.springframework.boot
spring-boot-maven-plugin
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
${basedir}/src/main/resources/generator/generatorConfig.xml
true
true
USE [wx]
GO
/****** Object: Table [dbo].[CM_Company] Script Date: 2018/11/24 20:14:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CM_Company](
[COID] [nchar](16) NOT NULL,
[NDID] [nchar](16) NULL,
[CPID] [nchar](12) NULL,
[CO_Base] [int] NULL,
[CO_Type] [int] NULL,
[LG_Code] [nvarchar](12) NULL,
[CO_Name] [nvarchar](64) NULL,
[CO_Addr] [nvarchar](96) NULL,
[CO_Time] [datetime] NULL,
[CO_State] [int] NULL,
[CO_Share] [int] NULL,
[CO_Phone] [nvarchar](32) NULL,
[CO_Spell] [nvarchar](32) NULL,
[CO_Linker] [nvarchar](16) NULL,
[CO_LkCode] [nvarchar](32) NULL,
[CO_E_Mail] [nvarchar](64) NULL,
[CO_BkType] [int] NULL,
[CO_BkCode] [nvarchar](64) NULL,
[CO_AcName] [nvarchar](64) NULL,
[CO_VcType] [nvarchar](16) NULL,
[CO_VcName] [nvarchar](64) NULL,
[CO_TxCode] [nvarchar](32) NULL,
[CO_BcFate] [int] NULL,
[CO_Stable] [int] NULL,
[CO_VWRate] [float] NULL,
[CO_Router] [nvarchar](256) NULL,
[CO_Server] [nvarchar](256) NULL,
[CO_ReMark] [nvarchar](960) NULL,
[CO_MapX] [float] NULL,
[CO_MapY] [float] NULL,
[CO_LaType] [int] NULL,
[CO_Starts] [int] NULL,
CONSTRAINT [PK_CM_Company] PRIMARY KEY CLUSTERED
(
[COID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[CM_Matcher] Script Date: 2018/11/24 20:14:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[CM_Matcher](
[COID] [nchar](16) NOT NULL,
[CR_Idx] [int] NULL,
[CR_Mode] [int] NULL,
[CT_Mode] [int] NULL,
[CR_Fate] [float] NULL,
[RG_Code] [nvarchar](12) NULL,
[RG_Name] [nvarchar](32) NULL,
[AR_Code] [nvarchar](12) NULL,
[AR_Name] [nvarchar](32) NULL,
[CM_Code] [nvarchar](16) NULL,
[CM_Name] [nvarchar](32) NULL,
[CR_Addr] [nvarchar](96) NULL,
[CR_Style] [int] NULL,
[CR_Grade] [int] NULL
) ON [PRIMARY]
GO
## 该配置节点为独立的节点,不要放在spring的节点下,导致配置无法被识别
mybatis.mapper-locations= classpath:mapping/*.xml
mybatis.type-aliases-package= com.wx.wlcx.model
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=wx
spring.datasource.username=sa
spring.datasource.password=manager
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.name= test
# 使用druid数据源
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters= stat
spring.datasource.maxActive= 20
spring.datasource.initialSize= 1
spring.datasource.maxWait= 60000
spring.datasource.minIdle= 1
spring.datasource.timeBetweenEvictionRunsMillis= 60000
spring.datasource.minEvictableIdleTimeMillis= 300000
spring.datasource.validationQuery= select 'x'
spring.datasource.testWhileIdle= true
spring.datasource.testOnBorrow= false
spring.datasource.testOnReturn= false
spring.datasource.poolPreparedStatements= true
spring.datasource.maxOpenPreparedStatements= 20
利用IDEA和generate 生成代码:点击 edit configuration
点击左上角的+号,添加maven插件, 填写如下信息:
配置好之后选择generate, 点击运行
运行成功后会生成po类,mapper接口, 以及对应的mapper.xml
CMMatcherMapper.xml
COID, CR_Idx, CR_Mode, CT_Mode, CR_Fate, RG_Code, RG_Name, AR_Code, AR_Name,
CM_Code, CM_Name, CR_Addr, CR_Style, CR_Grade
insert into CM_Matcher (COID, CR_Idx, CR_Mode,
CT_Mode, CR_Fate, RG_Code,
RG_Name, AR_Code, AR_Name,
CM_Code, CM_Name, CR_addr,
CR_Style, CR_Grade)
values (#{coid,jdbcType=NCHAR}, #{crIdx,jdbcType=INTEGER}, #{crMode,jdbcType=INTEGER},
#{ctMode,jdbcType=INTEGER}, #{crFate,jdbcType=DOUBLE}, #{rgCode,jdbcType=NVARCHAR},
#{rgName,jdbcType=NVARCHAR}, #{arCode,jdbcType=NVARCHAR}, #{arName,jdbcType=NVARCHAR},
#{cmCode,jdbcType=NVARCHAR}, #{cmName,jdbcType=NVARCHAR}, #{crAddr,jdbcType=NVARCHAR},
#{crStyle,jdbcType=INTEGER}, #{crGrade,jdbcType=INTEGER})
insert into CM_Matcher
COID,
CR_Idx,
CR_Mode,
CT_Mode,
CR_Fate,
RG_Code,
RG_Name,
AR_Code,
AR_Name,
CM_Code,
CM_Name,
CR_addr,
CR_Style,
CR_Grade,
#{coid,jdbcType=NCHAR},
#{crIdx,jdbcType=INTEGER},
#{crMode,jdbcType=INTEGER},
#{ctMode,jdbcType=INTEGER},
#{crFate,jdbcType=DOUBLE},
#{rgCode,jdbcType=NVARCHAR},
#{rgName,jdbcType=NVARCHAR},
#{arCode,jdbcType=NVARCHAR},
#{arName,jdbcType=NVARCHAR},
#{cmCode,jdbcType=NVARCHAR},
#{cmName,jdbcType=NVARCHAR},
#{crAddr,jdbcType=NVARCHAR},
#{crStyle,jdbcType=INTEGER},
#{crGrade,jdbcType=INTEGER},
##分页方法,手动添加
CMMatcherMapper.java
public interface CMMatcherMapper {
int insert(CMMatcher record);
int insertSelective(CMMatcher record);
List getAll();
}
CMMatcher.java
public class CMMatcher {
private String coid;
private Integer crIdx;
private Integer crMode;
private Integer ctMode;
private Double crFate;
private String rgCode;
private String rgName;
private String arCode;
private String arName;
private String cmCode;
private String cmName;
private String crAddr;
private Integer crStyle;
private Integer crGrade;
//get set
}
MatcherServiceImpl.java
@Service
public class MatcherServiceImpl implements MatcherService {
@Autowired
private MatcherMapper matcherMapper;
@Autowired
private CMMatcherMapper cmMatcherMapper;
@Override
public List getAll() {
return matcherMapper.getAll();
}
@Override
public List findAll(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return cmMatcherMapper.getAll();
}
}
这里分页插件的使用需要在配置文件中加入:
#分页插件
#pagehelper.dialect=sqlserver2012
pagehelper.reasonable=true
#支持通过 Mapper 接口参数来传递分页参数
pagehelper.support-methods-arguments=true
pagehelper.helper-dialect=sqlserver2012
pagehelper.params=count=countsql
pagehelper.pageSizeZero=true
如果是mysql数据库将sqlserver2012替换成mysql即可。
MatcherController.java
@RestController
public class MatcherController {
@Autowired
private MatcherService matcherService;
@GetMapping("/getAll")
public ResponseEntity getUserList (){
JsonResult r = new JsonResult();
try {
List users = matcherService.getAll();
r.setResult(users);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
@GetMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
public ResponseEntity findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
JsonResult r = new JsonResult();
try {
List users = matcherService.findAll(pageNum, pageSize);
r.setResult(users);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
}
分页的使用在server层使用PageHelper.startPage(pageNum, pageSize);
是不是分页就变得很方便了,不过在这里遇到了一个问题,因为sqlsevrer2012使用的分页不是标准的SQl, 所以需要在sql 语句中添加order by 排序,具体情况请参考:https://blog.csdn.net/qq_35623773/article/details/84488990
mybatis 注解版:
在配置文件中添加配置:
mybatis.type-aliases-package= com.wx.wlcx.model
CMMatcher.java
public class CMMatcher {
private String coid;
private int crInx;
private int crMode;
private int ctMode;
private float crFate;
private String rgCode;
private String arCode;
private String arName;
private String cmCode;
private String cmName;
private String crAddr;
private int crStyle;
private int crGrade;
//get set
}
MatcherMapper.java, 添加@Repository 注解, 而不是@Mapper注解
@Repository
public interface MatcherMapper {
@Select("select * from CM_Matcher")
@Results({
@Result(property = "coid", column = "COID"),
@Result(property = "crIdx", column = "CR_Idx"),
@Result(property = "crMode", column = "CR_Mode"),
@Result(property = "ctMode", column = "CT_Mode"),
@Result(property = "crFate", column = "CR_Fate"),
@Result(property = "rgCode", column = "RG_Code"),
@Result(property = "rgName", column = "RG_Name"),
@Result(property = "arCode", column = "AR_Code"),
@Result(property = "arName", column = "AR_Name"),
@Result(property = "cmCode", column = "CM_Code"),
@Result(property = "cmName", column = "CM_Name"),
@Result(property = "crAddr", column = "CR_Addr"),
@Result(property = "crStyle", column = "CR_Style"),
@Result(property = "crGrade", column = "CR_Grade")
})
List getAll();
}
另外还需要在application中添加注解扫描整个mapper包:
@SpringBootApplication
@MapperScan("com.wx.wlcx.mapper")
public class WlcxApplication {
public static void main(String[] args) {
SpringApplication.run(WlcxApplication.class, args);
}
}
controller,service 方法调用已在上面列出,可正常work.
配置druid数据源监控:
修改配置文件:
# 使用druid数据源
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters= stat
spring.datasource.maxActive= 20
spring.datasource.initialSize= 1
spring.datasource.maxWait= 60000
spring.datasource.minIdle= 1
spring.datasource.timeBetweenEvictionRunsMillis= 60000
spring.datasource.minEvictableIdleTimeMillis= 300000
spring.datasource.validationQuery= select 'x'
spring.datasource.testWhileIdle= true
spring.datasource.testOnBorrow= false
spring.datasource.testOnReturn= false
spring.datasource.poolPreparedStatements= true
spring.datasource.maxOpenPreparedStatements= 20
添加config配置类:
@Configuration
public class DruidConfig {
//访问地址:http://localhost:8080/wx/druid/login.html
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource durid(){
return new DruidDataSource();
}
//配置Druid的监控
//1.配置一个管理后台的sevlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map initParams = new HashMap();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
//设置ip白名单
initParams.put("allow", "");
//设置ip黑名单。deny优先级高于allow
initParams.put("deny", "192.168.10.125");
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map initParams = new HashMap();
//忽略过滤的形式
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//设置过滤器过滤路径
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
使用admin 123456 访问http://localhost:8080/wx/druid/login.html, 登录之后的界面为:
使用logback 配置日志管理:
创建logback.xml, springboot 官方建议使用 springboot-logback.xml 命名:
具体请看注释 logback-spring.xml
logback
info
${CONSOLE_LOG_PATTERN}
UTF-8
${log.path}/log_debug.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log
100MB
15
debug
ACCEPT
DENY
${log.path}/log_info.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log
100MB
15
info
ACCEPT
DENY
${log.path}/log_warn.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log
100MB
15
warn
ACCEPT
DENY
${log.path}/log_error.log
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
UTF-8
${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log
100MB
15
ERROR
ACCEPT
DENY
修改配置文件, 添加log路径:
logging.config=classpath:log/logback-spring.xml
logging.path=F:/demo/wxwl/log
最后,使用Thymeleaf整合前端,在这里遇到了一个关于依赖的问题被困扰了一下午, 如果你遇到同样的问题(能进controller, 但返回404), 请参考小哥的另一篇文章: “”“springboot 使用thymeleaf 报错 404. 跪求大佬解惑”
上配置文件:
spring.thymeleaf.cache=false
#spring.mvc.view.prefix=classpath:/templates/
#spring.mvc.view.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html
###THYMELEAF(ThymeleafAutoConfiguration)
## Enable template caching.
#spring.thymeleaf.cache=false
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
#spring.thymeleaf.servlet.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=UTF-8
## Comma-separated list of view names that should be excluded from resolution.
##spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html
##spring.thymeleaf.template-resolver-order=
## Order of the template resolver in the chain.
##spring.thymeleaf.view-names=
## Comma-separated list of view names that can be resolved.
controller:
@Controller
public class IndexController {
@RequestMapping("/test")
public String index() {
System.out.println("/index");
return "index";
}
}
index.html
Title
hello, boy
另外我们也可以使用rest分格返回页面:
@RestController
public class IndexController {
@GetMapping("/test")
public ModelAndView index(){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
return mv;
}
}
参考:
教程:使用Thymeleaf: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
pageHelper:
https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
springboot集成mybatis:
https://blog.csdn.net/winter_chen001/article/details/77249029
logback集成:
https://www.cnblogs.com/zhangjianbing/p/8992897.html
demo 代码地址:
https://github.com/MrGlen/wxwl
如果你觉得这篇文章对你有帮助,动动你的小手指点个赞吧!!_