开发工具
JB公司的IDEA开发包
一、创建Maven项目
Spirng boot项目在IDEA里头有很便捷的创建方式使用Spring Initalizr
可以直接创建spring-boot
项目,方便快捷。解决了很多常用的依赖包,如下图:
1.创建项目
2.选择web项目,sql下的mybatis,mysql,也可以根据自己的实际需要增加或者减少,文中以最简单为例
初始化完成后会进入到一个项目中,可以看看相应的文件结构。
二、添加我们需要的依赖,通过Maven进行操作
1.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.resetful</groupId>
<artifactId>resetful</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>resetful</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.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>
</properties>
<dependencies>
<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>
<!-- 引入log4j支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<!--提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.删除原有默认的配置文件,我们新建application.yml,spring boot以这种方式进行配置,更加方便快捷。application.yml文件内容格式如下:
spring:
datasource:
url: jdbc:mysql://localhost:3306/travel?serverTimezone=UTC&useSSL=false
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
type-aliases-package: com.resetful.model
# mapper-locations: classpath:mybatis/mapper/*.xml
# config-location: classpath:mybatis/mybatis-config.xml
3.log4j.properties
上面的pom中,我们禁用了原来的log文件输出,采用了log4j,这种方式更加的友好,方便我们查看的同时,更加高效的排查bug,配置如下:
# 全局配置
log4j.rootLogger=INFO, stdout, file
# mybatis的配置
log4j.logger.com.resetful.mapper.AreaMapper=TRACE
log4j.logger.com.resetful.mapper.UserMapper=TRACE
# 控制台输出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] - %m%n
# 文件输出配置
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %5p [%t] - %m%n
log4j.appender.file.File=/Users/xu/javaLog/log.log4j
log4j.appender.file.ImmediateFlush=true
三、整合mybatis
项目结构目录:
附上各个机构代码:
UserController
package com.resetful.controller;
import com.resetful.model.JsonResult;
import com.resetful.model.User;
import com.resetful.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Created by xu on 2017/11/24.
*/
@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") Integer 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") Integer 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") Integer 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);
}
}
Model-User
package com.resetful.model;
import lombok.Data;
import java.util.Date;
/**
* Created by xu on 2017/11/24.
*/
@Data
public class User {
private int id;
private String username;
private int age;
private Date ctm;
public User() {
}
public User(String username, int age) {
this.username = username;
this.age = age;
this.ctm = new Date();
}
}
service-UserService
package com.resetful.service;
import com.resetful.model.User;
import java.util.List;
/**
* Created by xu on 2017/11/24.
*/
public interface UserService {
User getUserById(Integer id);
public List<User> getUserList();
public int add(User user);
public int update(Integer id, User user);
public int delete(Integer id);
}
service-UserServiceimpl
package com.resetful.service.impl;
import com.resetful.mapper.UserMapper;
import com.resetful.model.User;
import com.resetful.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by xu on 2017/11/24.
*/
@Service
public class UserServiceimpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer 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(Integer id, User user) {
return userMapper.update(id, user);
}
@Override
public int delete(Integer id) {
return userMapper.delete(id);
}
}
第一种方法
整合mapper部分,有两种方式,第一种采用Class的方式引入
UserMapper
package com.resetful.mapper;
import com.resetful.model.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* Created by xu on 2017/11/24.
*/
public interface UserMapper {
@Select("SELECT * FROM tb_user WHERE id = #{id}")
User getUserById(Integer id);
@Select("SELECT * FROM tb_user")
public List<User> getUserList();
@Insert("insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())")
public int add(User user);
@Update("UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}")
public int update(@Param("id") Integer id, @Param("user") User user);
@Delete("DELETE from tb_user where id = #{id} ")
public int delete(Integer id);
}
ResetfulApplication入口文件
往ResetfulApplication添加@MapperScan("com.resetful.mapper")
注解
package com.resetful;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//配置MAPPER接口类未知
@MapperScan("com.resetful.mapper")
public class ResetfulApplication {
public static void main(String[] args) {
SpringApplication.run(ResetfulApplication.class, args);
}
}
第二种方法
需要在resource
下创建mybatis\mapper,在下面创建userMapper.xml
<?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.resetful.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.resetful.model.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List" >
id, username, age, ctm
</sql>
<select id="getUserList" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
</select>
<select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
WHERE id = #{id}
</select>
<insert id="add" parameterType="com.resetful.model.User" >
INSERT INTO
tb_user
(username,age,ctm)
VALUES
(#{username}, #{age}, now())
</insert>
<update id="update" parameterType="java.util.Map" >
UPDATE
tb_user
SET
username = #{user.username},age = #{user.age}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Integer" >
DELETE FROM
tb_user
WHERE
id = #{id}
</delete>
</mapper>
mybatis下创建配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
</typeAliases>
</configuration>
UserMapper需要稍作修改,添加
@Repository
注解
@Repository
public interface UserMapper {
User getUserById(Integer id);
public List<User> getUserList();
public int add(User user);
public int update(@Param("id") Integer id, @Param("user") User user);
public int delete(Integer id);
}
四、简要说明
选择其中一种,本人选择的是第一种方式,第二种方式也测试通过
sql:
创建数据库travel
,以及tb_user
表:
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '年龄',
`ctm` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
插入几条示例数据:
INSERT INTO `travel`.`tb_user` (`username`, `age`, `ctm`) VALUES('张三', '18', NOW()) ;
INSERT INTO `travel `.`tb_user` (`username`, `age`, `ctm`) VALUES('李四', '20', NOW()) ;
INSERT INTO `travel `.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;
项目访问,idea里头自动构建
- 直接启动
- 打包JAR包
mvn clean package -Dmaven.test.skip=true
在target目录下生成一个resetful-0.0.1-SNAPSHOT.jar
包,执行
java -jar resetful-0.0.1-SNAPSHOT.jar
访问http://localhost:8080/users,http://localhost:8080/user/1
可看到效果