发表于: 2017-08-05 23:29:56
2 1176
今天完成的事情:项目改BUG,上篇日报有很多不对的地方,这次换成了基于注解springboot整合mybatis
一、数据准备
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`qq` varchar(255) DEFAULT NULL,
`job` varchar(255) DEFAULT NULL,
`regeneration` varchar(255) DEFAULT NULL,
`school` varchar(255) DEFAULT NULL,
`link` varchar(255) DEFAULT NULL,
`declaration` varchar(255) DEFAULT NULL,
`senior` varchar(255) DEFAULT NULL,
`create_time` bigint(20) DEFAULT NULL,
`update_time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2126 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1416', '程凯', '1210977699', 'Java工程师', '2017年3月20日', '中国地质大学江城学院', 'http://www.jnshu.com/daily/17642?uid=9299', '心之所向,素履以往', '李涛', null, null);
INSERT INTO `user` VALUES ('1693', '刘家铭', '286683815', 'Java工程师', '2017年4月19日', '武汉工程职业技术学院', 'http://www.jnshu.com/daily/20789?uid=11009', '老大最帅', '吴志勇', null, null);
INSERT INTO `user` VALUES ('2118', '甘乐乐', '984802926', 'Java工程师', '2017年7月24日', '武汉科技大学', 'http://www.jnshu.com/daily/28718?dailyType=others&total=8&page=1&uid=13195&sort=0&orderBy=3', '终一生光阴极有限,且浪费且珍惜。', '严恒', null, null);
INSERT INTO `user` VALUES ('2124', '宋哲明', '920084245', 'Java工程师', '2017年7月18日', '长江大学', 'http://www.jnshu.com/daily/27686?dailyType=others&total=7&page=7&uid=13516&sort=0&orderBy=3', '向死而生', '张鑫', null, null);
二、引入依赖
<dependencies>
<!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- exclude掉spring-boot的默认log配置 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- hikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
三、配置文件
application.properties
#配置数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=wyc19960210
#指定hikari连接池
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
#连接池配置信息
#<!-- 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count) -->
spring.datasource.hikari.maximum-pool-size=10
#<!-- 连接池中允许的最小连接数。缺省值:10;官方建议与最大连接数保持一致 -->
spring.datasource.hikari.minimum-idle=10
#<!-- 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒 -->
spring.datasource.hikari.connection-timeout=30000
#<!-- 控制从池返回的连接的默认自动提交行为。它是一个布尔值。默认值:true -->
spring.datasource.hikari.auto-commit=true
#<!-- 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒, -->
spring.datasource.hikari.max-lifetime=180000
#<!-- 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟 -->
spring.datasource.hikari.idle-timeout=600000
#log4j2配置文件地址
logging.config=classpath:log4j2.xml
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="300">
<properties>
<property name="LOG_HOME">D:/logs</property>
<property name="FILE_NAME">mylog</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingRandomAccessFile name="MyFile"
fileName="${LOG_HOME}/${FILE_NAME}.log"
filePattern="${LOG_HOME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd HH-mm}-%i.log">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" />
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Logger name="mylog" level="trace" additivity="false">
<AppenderRef ref="MyFile" />
</Logger>
<Root level="info">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
四、代码
这次springboot整合mybatis是无配置注解版
实体类User
package com.wyc.task1.domain;
import java.io.Serializable;
public class User implements Serializable{
private Long id;
private String name;
private String qq;
private String job;
private String regeneration;
private String school;
private String link;
private String declaration;
private String senior;
private Long createTime;private Long updateTime;
省略SET GET
}
UserMapper
package com.wyc.task1.dao;
import com.wyc.task1.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper{
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(long id);
@Select("SELECT * FROM user")
public List<User> getUserList();
@Insert("insert into user(name, qq, job) values(#{name}, #{qq}, #{job})")
public int add(User user);
@Update("UPDATE user SET name = #{user.name} , qq = #{user.qq} WHERE id = #{id}")
public int update(@Param("id") long id, @Param("user") User user);
@Delete("DELETE from user where id = #{id} ")
public int delete(long id);
}
UserService
package com.wyc.task1.service;
import com.wyc.task1.domain.User;
import java.util.List;
public interface UserService {
User getUserById(long id);
public List<User> getUserList();
public int add(User user);
public int update(long id, User user);
public int delete(long id);
}
UserServiceImpl
package com.wyc.task1.service.Impl;
import com.wyc.task1.dao.UserMapper;
import com.wyc.task1.domain.User;
import com.wyc.task1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(long id) {
return userMapper.getUserById(id);
}
@Override
public List<User> getUserList() {
return userMapper.getUserList();
}
@Override
public int add(User user) {
return userMapper.add(user);
}
@Override
public int update(long id, User user) {
return userMapper.update(id, user);
}
@Override
public int delete(long id) {
return userMapper.delete(id);
}
}
JsonResult
package com.wyc.task1.util;
public class JsonResult {
private String status = null;
private Object result = null;
public JsonResult status(String status) {
this.status = status;
return this;}
省略SET GET
}
UserController
package com.wyc.task1.controller;
import com.wyc.task1.domain.User;
import com.wyc.task1.service.UserService;
import com.wyc.task1.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 根据ID查询用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") long id){
JsonResult r = new JsonResult();
try {
User user = userService.getUserById(id);
r.setResult(user);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 查询用户列表
* @return
*/
@RequestMapping(value = "users", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
JsonResult r = new JsonResult();
try {
List<User> users = userService.getUserList();
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);
}
/**
* 添加用户
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<JsonResult> add (@RequestBody User user){
JsonResult r = new JsonResult();
try {
int orderId = userService.add(user);
if (orderId < 0) {
r.setResult(orderId);
r.setStatus("fail");
} else {
r.setResult(orderId);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id删除用户
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") long id){
JsonResult r = new JsonResult();
try {
int ret = userService.delete(id);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id修改用户信息
* @param user
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> update (@PathVariable("id") long id, @RequestBody User user){
JsonResult r = new JsonResult();
try {
int ret = userService.update(id, user);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
}
Task1Application
package com.wyc.task1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Task1Application {
public static void main(String[] args) {
SpringApplication.run(Task1Application.class, args);
}
}
五、postman测试
根据ID取得用户信息,成功返回状态ok,数据
添加用户
六、修改host文件自定义域名
通过软媒魔方来修改HOST文件如下图所示
成功连接取得数据
明天计划的事情:springmvc再复习一下
遇到的问题:之前的配置文件
#配置数据库连接信息
spring.datasource.hikari.jdbc-url=jdbc:mysql://localhost:3306/test
spring.datasource.hikari.username=root
spring.datasource.hikari.password=!Wyc!19960210
spring.datasource.hikari.driver-class-name=com.mysql.jdbc.Driver
这样用会报
Cannot determine embedded database driver class for database type NONE
引以为鉴
收获:mysql关键字,建表的时候需要注意不要建成MYssql关键字了,数据会死活存不进去。
评论