本文共 3295 字,大约阅读时间需要 10 分钟。
第一步创建项目:
创建项目地址:
接下来就下载到本地了 跟着加压
接着用idea打开:等待资源下载完成
转存失败
我写了个简单的:增删改查
项目结构:
dao层:
package com.nf147.demo.dao;import com.nf147.demo.entity.News;import org.springframework.data.jpa.repository.JpaRepository;public interface NewsMapper extends JpaRepository{ //第一个参数是实体类,第二个是id的类型
}
entity层:
package com.nf147.demo.entity;import javax.persistence.*;@Entity@Table(name = "news") //表名public class News { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) //标明该字段是自动增长 private int id; private String title; private String body; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getBody() { return body; } public void setBody(String body) { this.body = body; }}
service层:
package com.nf147.demo.service;import com.nf147.demo.entity.News;import java.util.List;public interface NewsService { ListlistAll(); void add (News news); void del (int id); void update(News news);}
实现服务接口:
package com.nf147.demo.service;import com.nf147.demo.dao.NewsMapper;import com.nf147.demo.entity.News;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class NewsServiceImp implements NewsService { @Autowired private NewsMapper newsMapper; @Override @Cacheable("listNews") public ListlistAll() { return newsMapper.findAll(); } @Override public void add(News news) { newsMapper.save(news); } @Override public void del(int id) { newsMapper.deleteById(id); } @Override public void update(News news) { newsMapper.save(news); }}
controller层:
package com.nf147.demo.controller;import com.nf147.demo.entity.News;import com.nf147.demo.service.NewsServiceImp;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestControllerpublic class NewsController { @Autowired private NewsServiceImp newsServiceImp; //查询 @RequestMapping(value = "/listNews", method = RequestMethod.GET) public ListgetNews() { return newsServiceImp.listAll(); } //添加 http://localhost:8082/listNewsAdd?title=标题&body=随便给的内容 @RequestMapping(value = "/listNewsAdd", method = RequestMethod.GET) public void add(News news) { newsServiceImp.add(news); } //删除 //地址栏写法 http://localhost:8082/listNewsdel?id=7 @RequestMapping(value = "/listNewsdel", method = RequestMethod.GET) public void del(int id) { newsServiceImp.del(id); } //修改 //地址栏写法 http://localhost:8082/listNewsupdate?id=6&title=好好&body=学习 @RequestMapping(value = "/listNewsupdate", method = RequestMethod.GET) public void del(News news) { newsServiceImp.update(news); }}
测试:
转存失败
项目下载地址:
转载地址:http://zthgn.baihongyu.com/