(1) MySQL의 데이터 시트 제조
다음과 같이 첫째, 뉴스 테이블의 구조는 테이블은 다음과 같습니다
![4824974 - cc14132c8fc97e06.jpg](https://upload-images.jianshu.io/upload_images/4824974-cc14132c8fc97e06.jpg)
콘텐츠 데이터의 표는 다음과 같습니다
![4824974-905e40d977440e43.jpg](https://upload-images.jianshu.io/upload_images/4824974-905e40d977440e43.jpg)
2. 관련
2.1 치어 구성 파일
통합 봄 부팅에 MyBatis로로 인해, pom.xml 파일 (Maven 프로젝트)를 수정할 필요는 MySQL의 설정으로 MyBatis로를 추가 :
vscode에서 pom.xml 파일을 선택하고 마우스 오른쪽 버튼으로 클릭하고 편집 선발
![4824974-0e5638ed8bbc14e5.jpg](https://upload-images.jianshu.io/upload_images/4824974-0e5638ed8bbc14e5.jpg)
동시에 체크 MySQL의 입력, 옵션으로 MyBatis로 :
![4824974-83d6779348fcd70a.jpg](https://upload-images.jianshu.io/upload_images/4824974-83d6779348fcd70a.jpg)
두 개 이상의 종속적 인 선택 사항의 업데이트의 pom.xml 후 :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
<scope>compile</scope>
</dependency>
2.2 구성 옵션 application.properties
연결 문자열 application.properties 구성 파일 등 데이터베이스 계정, 암호를 기입하는 것입니다 :
#application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/zlfj?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=${你的数据库密码}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.3 엔티티 클래스 만들기
프로젝트 파일 디렉토리는 다음과 같습니다 :
![4824974-2ad384547cd07cbd.jpg](https://upload-images.jianshu.io/upload_images/4824974-2ad384547cd07cbd.jpg)
는 SQL 테이블과 자바 파일을 매핑하는 데 사용 newsentity 클래스를 생성하는 단계;
//NewsEntity.java
public class NewsEntity implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String title;
private String content;
private Date gmttime;
/*
**省略getset 方法,记得写
*/
}
2.4 생성 다오 층은 특정 데이터 조작을 정의
(1) 주석 스타일을 사용하여
다오 NewsDao.java은 주석 층과 데이터베이스 작업을 구현하는 쓰기 과정에서 정의 :
@Mapper
public interface NewsDao{
/**
* 查询单个
* @return
*/
@Select("SELECT * from news WHERE id=#{id}")
NewsEntity queryObject(@Param("id") Long id);
}
엔티티가 클래스에 전달되면, 당신은 결과를 주석지도를 조회해야합니다
/**
* 保存
* @return
*/
@Results(
{
@Result(property = "id", column = "id", id = true),
@Result(property = "title", column = "title"),
@Result(property = "content", column = "content"),
@Result(property = "gmttime", column = "gmtTime")
}
)
@Insert("insert into news (title,content,gmtTime) values(#{title},#{content},#{gmttime})")
void save(NewsEntity news);
/**
* 修改
* @return
*/
@Results(
{
@Result(property = "id", column = "id", id = true),
@Result(property = "title", column = "title"),
@Result(property = "content", column = "content"),
@Result(property = "gmttime", column = "gmtTime")
}
)
@Update("update news set `title`=#{title},`content`=#{content},`gmtTime`=#{gmttime} where id=#{id}")
void update(NewsEntity news);
(2) XML 방식을 사용하여
주석 매퍼 DAO를 첨가하면서 먼저 각 동작을 DAO 층을 정의
package com.zhb.nongboot.dao;
import java.util.List;
import java.util.Map;
import com.zhb.nongboot.entity.NewsEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface NewsDao{
/**
* 查询
* @return
*/
NewsEntity queryObject(Long id);
/**
* 查询列表
* @return
*/
List<NewsEntity> queryList(Map<String, Object> map);
/**
* 查询总数
* @return
*/
int queryTotal(Map<String, Object> map);
/**
* 保存
* @return
*/
void save(NewsEntity news);
/**
* 修改
* @return
*/
void update(NewsEntity news);
/**
* 删除
* @return
*/
void delete(Long id);
}
같은 디렉토리 NewsDao.java, 새로운 NewsDao.xml 파일은 자사의 특정 SQL 데이터베이스 작업을 정의합니다 :
<?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.zhb.nongboot.dao.NewsDao">
<resultMap id="newsMap" type="com.zhb.nongboot.entity.NewsEntity">
<result property="id" column="id"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<result property="gmttime" column="gmtTime"/>
</resultMap>
<select id="queryObject" resultType="com.zhb.nongboot.entity.NewsEntity">
select * from news where id = #{value}
</select>
<select id="queryList" resultType="com.zhb.nongboot.entity.NewsEntity">
select * from news where 1=1
<choose>
<when test="sidx != null and sidx.trim() != ''">
order by ${sidx} ${order}
</when>
<otherwise>
order by id desc
</otherwise>
</choose>
<if test="offset != null and limit != null">
limit #{offset}, #{limit}
</if>
</select>
<select id="queryTotal" resultType="int">
select count(*) from news where 1=1
</select>
<insert id="save" parameterType="com.zhb.nongboot.entity.NewsEntity" useGeneratedKeys="true" keyProperty="id">
insert into news
(
`title`,
`content`,
`gmtTime`
)
values
(
#{title},
#{content},
#{gmttime}
)
</insert>
<update id="update" parameterType="com.zhb.nongboot.entity.NewsEntity">
update news
<set>
<if test="title != null">`title` = #{title},</if>
<if test="content != null">`content` = #{content},</if>
<if test="gmttime != null">`gmtTime` = #{gmttime}</if>
</set>
where id = #{id}
</update>
<delete id="delete">
delete from news where id = #{value}
</delete>
<delete id="deleteBatch">
delete from news where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
2.5 방법 및 서비스 계층 인터페이스 정의 (특히 서비스 로직 층)을 구현
여기에서 우리는 추가 및 삭제 소식이 테이블의 작동에, 그래서 그것의 인터페이스 정의는 다음과 같습니다
NewsService.java
import java.util.List;
import java.util.Map;
import com.zhb.nongboot.entity.NewsEntity;
import org.springframework.stereotype.Service;
public interface NewsService{
/**
* 查询
* @return
*/
NewsEntity queryObject(Long id);
/**
* 查询列表
* @return
*/
List<NewsEntity> queryList(Map<String, Object> map);
/**
* 查询总数
* @return
*/
int queryTotal(Map<String, Object> map);
/**
* 保存
* @return
*/
void save(NewsEntity news);
/**
* 修改
* @return
*/
void update(NewsEntity news);
/**
* 删除
* @return
*/
void delete(Long id);
}
구체적인 실현을 서비스 :
//NewsServiceImpl.java
package com.zhb.nongboot.service.impl;
import java.util.List;
import java.util.Map;
import com.zhb.nongboot.dao.NewsDao;
import com.zhb.nongboot.entity.NewsEntity;
import com.zhb.nongboot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class NewsServiceImpl implements NewsService{
@Autowired
private NewsDao newsDao;
@Override
public NewsEntity queryObject(Long id){
NewsEntity entity = newsDao.queryObject(id);
return entity;
}
@Override
public List<NewsEntity> queryList(Map<String, Object> map){
List<NewsEntity> list = newsDao.queryList(map);
return list;
}
@Override
public int queryTotal(Map<String, Object> map){
return newsDao.queryTotal(map);
}
@Override
public void save(NewsEntity news){
newsDao.save(news);
}
@Override
public void update(NewsEntity news){
newsDao.update(news);
}
@Override
public void delete(Long id){
newsDao.delete(id);
}
}
참고 : 우리는 서비스를 정의 여기에 있기 때문에, 봄, 봄의 NewsService이 컨테이너의 스프링 통합 관리 넘겨, 등록 할 (제어의 IOC 반전)
그래서 공용 클래스는 NewsService이 코멘트 @Service을 추가 기억에 NewsServiceImpl 정의 구현
@Service
public class NewsServiceImpl implements NewsService{
그렇지 않으면, 봄의 서비스를 찾을 수없는 불평 할 것이다.
2.6controller 층 : 등록 경로 수신 파라미터
간단한 보존 방법이 정상으로 여기에서 우리는 query 메소드를 테스트 :
import java.util.Date;
import java.util.HashMap;
import com.zhb.nongboot.entity.NewsEntity;
import com.zhb.nongboot.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("news")
public class NewsController {
@Autowired
private NewsService newsService;
/**
* 信息
*/
@RequestMapping("/info/{id}")
public NewsEntity info(@PathVariable("id") Long id){
NewsEntity news = newsService.queryObject(id);
return news;
}
@RequestMapping("save/{name}")
public HashMap<String,String> save(@PathVariable("name") String name){
NewsEntity news = new NewsEntity();
news.setTitle(name);
news.setContent("新增通知成功");
news.setGmttime(new Date());
newsService.save(news);
return (HashMap<String, String>) new HashMap<>().put("message", "ok");
}
/ 뉴스 / 정보 / 2 돌아 표 2 뉴스 행의 ID에 액세스 할 때.
/ 뉴스 / 저장 / titlename 시간을 액세스 할 때, 레코드 titlename에 타이틀을 추가합니다.
테스트 :
한 줄 쿼리 기록 :
![4824974-7de63304a93bb249.jpg](https://upload-images.jianshu.io/upload_images/4824974-7de63304a93bb249.jpg)
저장
![4824974-390646b35e5840f3.jpg](https://upload-images.jianshu.io/upload_images/4824974-390646b35e5840f3.jpg)
![4824974-57d6c9eccdd335de.jpg](https://upload-images.jianshu.io/upload_images/4824974-57d6c9eccdd335de.jpg)
이 테스트는 성공;