首先创建maven工程
引入依赖(我的实体类在ihrm_common_model模块中)
如果是自己练手的话可以全部写到一个模块中
<?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">
<parent>
<artifactId>ihrm_parent</artifactId>
<groupId>com.ihrm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ihrm_company</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.ihrm</groupId>
<artifactId>ihrm_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.ihrm</groupId>
<artifactId>ihrm_common_model</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
(2)添加配置文件application.yml
#服务配置
server:
port:9001
#spring配置
#应用配置
#数据库连接池
#jpa
spring:
application:
name: ihrm-company #指定服务名
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ihrm?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
database: MySQL
show-sql: true
open-in-view: true
(3)配置启动类
package com.ihrm.company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
//配置springBoot的包扫描
@SpringBootApplication(scanBasePackages = "com.ihrm.company")
//配置jpa注解的扫描
@EntityScan(value = "com.ihrm.domain.company")
public class CompanyApplication {
//启动方法
public static void main(String[] args) {
SpringApplication.run(CompanyApplication.class,args);
}
}
完成增删改查
(1)创建实体类(domain)
package com.ihrm.domain.company;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/**
* <dependency>
* <groupId>org.projectlombok</groupId>
* <artifactId>lombok</artifactId>
* <version>1.16.16</version>
* </dependency>
* 使用
*/
@Entity
@Table(name = "co_company")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Company {
private static final long serialVersionUID = 594829320797158219L;
//ID
@Id
private String id;
/**
* 公司名称
*/
private String name;
/**
* 企业登录账号ID
*/
private String managerId;
/**
* 当前版本
*/
private String version;
/**
* 续期时间
*/
private Date renewalDate;
/**
* 到期时间
*/
private Date expirationDate;
/**
* 公司地区
*/
private String companyArea;
/**
* 公司地址
*/
private String companyAddress;
/**
* 营业执照-图片ID
*/
private String businessLicenseId;
/**
* 法人代表
*/
private String legalRepresentative;
/**
* 公司电话
*/
private String companyPhone;
/**
* 邮箱
*/
private String mailbox;
/**
* 公司规模
*/
private String companySize;
/**
* 所属行业
*/
private String industry;
/**
* 备注
*/
private String remarks;
/**
* 审核状态
*/
private String auditState;
/**
* 状态
*/
private Integer state;
/**
* 当前余额
*/
private Double balance;
/**
* 创建时间
*/
private Date createTime;
}
(2)持久层(dao)
package com.ihrm.company.dao;
import com.ihrm.domain.company.Company;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* 自定义dao接口继承
* JpaRepository<实体类, 主键类型>
* JpaSpecificationExecutor<实体类>
*/
public interface CompanyDao extends JpaRepository<Company, String>, JpaSpecificationExecutor<Company> {
}
test测试
package com.ihrm.company;
import com.ihrm.company.dao.CompanyDao;
import com.ihrm.domain.company.Company;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class CompanyTest {
@Autowired
private CompanyDao companyDao;
//save:保存或更新(id),没有id时保存,有id时更新
//deleteById:根据id删除
//findAll:查询所有
//findById:根据id查询
@Test
public void test(){
Company company = companyDao.findById("1").get();
System.out.println(company);
}
}
输出:
JpaRepository提供了基本的增删改查 JpaSpecificationExecutor用于做复杂的条件查询
建表语句
/*
MySQL Data Transfer
Source Host: localhost
Source Database: ihrm
Target Host: localhost
Target Database: ihrm
Date: 2019-02-23 17:23:33
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for co_company
-- ----------------------------
CREATE TABLE `co_company` (
`id` varchar(40) NOT NULL COMMENT 'ID',
`name` varchar(255) NOT NULL COMMENT '公司名称',
`manager_id` varchar(255) NOT NULL COMMENT '企业登录账号ID',
`version` varchar(255) DEFAULT NULL COMMENT '当前版本',
`renewal_date` datetime DEFAULT NULL COMMENT '续期时间',
`expiration_date` datetime DEFAULT NULL COMMENT '到期时间',
`company_area` varchar(255) DEFAULT NULL COMMENT '公司地区',
`company_address` text COMMENT '公司地址',
`business_license_id` varchar(255) DEFAULT NULL COMMENT '营业执照-图片ID',
`legal_representative` varchar(255) DEFAULT NULL COMMENT '法人代表',
`company_phone` varchar(255) DEFAULT NULL COMMENT '公司电话',
`mailbox` varchar(255) DEFAULT NULL COMMENT '邮箱',
`company_size` varchar(255) DEFAULT NULL COMMENT '公司规模',
`industry` varchar(255) DEFAULT NULL COMMENT '所属行业',
`remarks` text COMMENT '备注',
`audit_state` varchar(255) DEFAULT NULL COMMENT '审核状态',
`state` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态',
`balance` double NOT NULL COMMENT '当前余额',
`create_time` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `co_company` VALUES ('1', '大米公司', 'dami', '1', '2019-02-28 16:53:14', '2019-02-28 16:53:23', '佛山', '大良', '43254325432543543', '雷军', '13322224444', '13322224444@163.com', '大', '科技', '0', '0', '1', '0', '2019-02-23 16:55:24');
(3)业务逻辑层(service)
package com.ihrm.company.service;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.company.dao.CompanyDao;
import com.ihrm.domain.company.Company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class CompanyServce {
@Autowired
private CompanyDao companyDao;
@Autowired
private IdWorker idworker;
/**
* 保存
* company参数可能没有id
*/
public Company add(Company company) {
//基本属性设置
company.setId(idworker.nextId() + "");
company.setCreateTime(new Date());
company.setState(1);//启用
company.setAuditState("0");//待审核
company.setBalance(0d);
return companyDao.save(company);
}
public Company update(Company company) {
return companyDao.save(company);
}
public Company findById(String id) {
return companyDao.findById(id).get();
}
public void deleteById(String id) {
companyDao.deleteById(id);
}
public List<Company> findAll() {
return companyDao.findAll();
}
}
控制层
package com.ihrm.company.controller;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.company.service.CompanyServce;
import com.ihrm.domain.company.Company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/company")
public class CompanyController {
@Autowired
private CompanyServce companyServce;
/**
* 添加企业
*/
@RequestMapping(value = "", method = RequestMethod.POST)
public Result add(@RequestBody Company company) {
companyServce.add(company);
return new Result(ResultCode.SUCCESS);
}
/**
* 根据id更新企业
*/
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
//@PathVariable(value = "id") String id---表示从地址中获取到为id的参数,赋值给spring id
public Result update(@PathVariable(name = "id") String id, @RequestBody Company company) {
company.setId(id);
Company one = new Company();
one.setName(company.getName());
one.setRemarks(company.getRemarks());
one.setState(company.getState());
one.setAuditState(company.getAuditState());
companyServce.update(company);
return new Result(ResultCode.SUCCESS);
}
/**
* 根据id删除企业
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Result deleteById(@PathVariable(name = "id") String id) {
companyServce.deleteById(id);
return new Result(ResultCode.SUCCESS);
}
/**
* 根据ID获取公司信息
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Result findById(@PathVariable(name = "id") String id) {
Company company = companyServce.findById(id);
return new Result(ResultCode.SUCCESS,company);
}
/**
* 获取企业列表
*/
@RequestMapping(value = "", method = RequestMethod.GET)
public Result findAll() {
List<Company> companyList = companyServce.findAll();
return new Result(ResultCode.SUCCESS,companyList);
}
}
entity实体类
Result
package com.ihrm.common.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Result {
private boolean success;//是否成功
private Integer code;// 返回码
private String message;//返回信息
private Object data;// 返回数据
public Result(ResultCode code) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
}
public Result(ResultCode code,Object data) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
this.data = data;
}
public Result(Integer code,String message,boolean success) {
this.code = code;
this.message = message;
this.success = success;
}
public static Result SUCCESS(){
return new Result(ResultCode.SUCCESS);
}
public static Result ERROR(){
return new Result(ResultCode.SERVER_ERROR);
}
public static Result FAIL(){
return new Result(ResultCode.FAIL);
}
}
ResultCode
package com.ihrm.common.entity;
/**
* 公共的返回码
*/
public enum ResultCode {
SUCCESS(true,10000,"操作成功!"),
//---系统错误返回码-----
FAIL(false,10001,"操作失败"),
UNAUTHENTICATED(false,10002,"您还未登录"),
UNAUTHORISE(false,10003,"权限不足"),
SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!");
//---用户操作返回码----
//---企业操作返回码----
//---权限操作返回码----
//---其他操作返回码----
//操作是否成功
boolean success;
//操作代码
int code;
//提示信息
String message;
ResultCode(boolean success,int code, String message){
this.success = success;
this.code = code;
this.message = message;
}
public boolean success() {
return success;
}
public int code() {
return code;
}
public String message() {
return message;
}
}
IdWorker在上一篇雪花算法中已经写过代码