springboot 통합 Mybatis,JPA,Redis 의 예제 코드
13495 단어 springbootMybatisJPARedis
springboot 프로젝트 에서 저 희 는 ORM 프레임 워 크 로 데이터 베 이 스 를 조작 하 는 것 이 매우 편리 합 니 다.다음은 mysql,spring data jpa,redis 를 각각 통합 합 니 다.급행 열 차 를 느껴 봅 시다.
우 리 는 먼저 springboot 프로젝트 를 만 들 고 만 든 후에 우 리 는 한 걸음 한 걸음 실천 합 시다.
mybatis 사용 하기
도입 의존:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
설정 추가application.properties 에 데이터베이스 연결 설정 을 추가 합 니 다.
# Mysql : com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
sql 만 들 기다음은 sql 문 구 를 만 듭 니 다.우리 뒤에서 테스트 할 수 있 게 해 주세요.
#
CREATE DATABASE springbootdata;
#
USE springbootdata;
# t_article
DROP TABLE IF EXISTS t_article;
CREATE TABLE t_article (
id int(20) NOT NULL AUTO_INCREMENT COMMENT ' id',
title varchar(200) DEFAULT NULL COMMENT ' ',
content longtext COMMENT ' ',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO t_article VALUES ('1', 'Spring Boot ', ' ...');
INSERT INTO t_article VALUES ('2', 'Spring Cloud ', ' ...');
# t_comment
DROP TABLE IF EXISTS t_comment;
CREATE TABLE t_comment (
id int(20) NOT NULL AUTO_INCREMENT COMMENT ' id',
content longtext COMMENT ' ',
author varchar(200) DEFAULT NULL COMMENT ' ',
a_id int(20) DEFAULT NULL COMMENT ' id',
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO t_comment VALUES ('1', ' 、 ', 'luccy', '1');
INSERT INTO t_comment VALUES ('2', ' ', 'tom', '1');
INSERT INTO t_comment VALUES ('3', ' ', 'eric', '1');
INSERT INTO t_comment VALUES ('4', ' , ', ' ', '1');
INSERT INTO t_comment VALUES ('5', ' ', ' ', '2');
실체 만 들 기그 다음 에 우 리 는 실체 류 를 만들어 야 합 니 다.우 리 는 t 를 만 듭 니 다.comment 표 에 대응 하 는 실체 클래스 죠?
public class Comment {
private Integer id; // id
private String content; //
private String author; //
private Integer aId; // :
//getter()/setter()
mapper 생 성위 에서 다 만 든 후에 우 리 는 당연히 mapper 인 터 페 이 스 를 만 들 고 데이터 베 이 스 를 조작 하 러 왔 습 니 다.여기 서 우 리 는 가장 간단 하고 주 해 를 사용 하 는 방식 을 사용 합 니 다.
// mybatis , springboot , ,
@Mapper
public interface CommentMapper {
// id
@Select("select * from t_comment where id = #{id}")
Comment findById(Integer id);
}
생 성 테스트위 에 서 는 이렇게 해서 spring boot 와 my batis 의 통합 을 완 성 했 습 니 다.다음 에 테스트 해 보 겠 습 니 다.
pom.xml 파일 에 도입:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
테스트 클래스 에서 작성:
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootQuickstartApplicationTests {
@Autowired
private CommentMapper commentMapper;
@Test
void contextLoads() {
Comment comment = commentMapper.findById(1);
System.out.println(comment);
}
}
효과:my batis 통합 이 성공 적 이라는 것 을 증명 합 니 다.간단 하지 않 습 니까?하나의 starter 만 도입 하면 my batis 기능 을 정상적으로 사용 할 수 있 습 니 다.
xml 기반 방식
위의 것 은 주 해 를 바탕 으로 하 는 것 이 고 우 리 는 xml 를 바탕 으로 할 수 있다.우 리 는 mapper 에 sql 을 쓰 지 않 고 xml 에 작성 합 니 다.여기 ArticleMapper 를 예 로 들 면
@Mapper
public interface ArticleMapper {
// id
public Article selectArticle(Integer id);
}
대응 하 는 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="cn.quellanan.springbootquickstart.mapper.ArticleMapper">
<select id="selectArticle" parameterType="int" resultType="article">
select * from t_article where id = #{id}
</select>
</mapper>
설정 파일 에 mapper.xml 의 위 치 를 지정 해 야 합 니 다.지정 하지 않 으 면 mapper 와 같은 디 렉 터 리 가 필요 합 니 다.resultType 은 설정 파일 에 별명 을 지정 할 수 있 습 니 다.
# mapper
mybatis.configuration.map-underscore-to-camel-case=true
# mybatis xml
mybatis.mapper-locations=classpath:mapper/*.xml
# mybatis
mybatis.type-aliases-package=cn.quellanan.springbootquickstart.pojo
우리 다시 테스트 방법 을 써 서 테스트 해 보 자.
@Autowired
private ArticleMapper articleMapper;
@Test
public void selectArticle(){
Article article = articleMapper.selectArticle(1);
System.out.println(article);
}
이렇게 spring boot 통합 my batis 기본 은 ok 입 니 다.
jpa 사용
위 에 우리 springboot 전체 my batis 는 스스로 sql 을 써 야 합 니 다.그 다음 에 우 리 는 몰래 게 으 름 을 피 워 springData JPA 를 통합 해 야 합 니 다.앞서 말 했 듯 이 springboot data jpa 는 일종 의 규범 으로 이러한 규범 을 실현 하 는 프레임 워 크 를 사용 해 야 하기 때문에 앞 에 hibenate 를 사용 했다.하지만 springboot 에 서 는 이렇게 번 거 롭 지 않 아 도 됩 니 다.hibenate 와 관련 된 jar 를 도입 하지 않 아 도 됩 니 다.저희 도 사용 할 수 있 습 니 다.다음은 어디 보 자.
도입 의존
첫 번 째 단 계 는 pom 파일 에 의존 도 를 도입 해 야 합 니 다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
실체 클래스 와 표 의 관 계 를 맺다의존 을 도입 한 후에 우 리 는 실체 류 와 표 와 표 속성 을 연결 시 켜 야 한다.우 리 는 여전히 Comment 같은 부류 로수정 을 진행 하 다.
@Entity
@Table(name = "t_comment")
public class Comment {
@Id // id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; // id
private String content; //
private String author; //
@Column(name = "a_id")
private Integer aId; // :
//getter()/setter()
}
우선@Entity 표지 라 는 실체 클래스 가 필요 합 니 다.처리 할 수 있 습 니 다.@Table()데이터베이스 에 대응 하 는 표 이름 을 설명 합 니 다.
@Id 는 테이블 의 메 인 키 를 지정 하 는 데 사 용 됩 니 다.
@Generated Value()는 메 인 키 의 종 류 를 지정 합 니 다.
@Column 은 이 속성 에 대응 하 는 표 의 열 이름 을 지정 하 는 데 사 용 됩 니 다.클래스 속성 과 표 열 이름 이 일치 하면 지정 하지 않 고 일치 하지 않 으 면 지정 해 야 합 니 다.
인터페이스 만 들 기
우 리 는 Jpa Repository 를 계승 하기 위해 인 터 페 이 스 를 만 들 었 다.두 개의 매개 변수 가 있 는데 첫 번 째 매개 변 수 는 대응 하 는 실체 류 대상 이 고 두 번 째 매개 변수 메 인 키 데이터 형식 입 니 다.
public interface CommentRepository extends JpaRepository<Comment, Integer> {
}
테스트이제 우 리 는 테스트 를 진행 할 수 있다.
@Autowired
private CommentRepository commentRepository;
@Test
public void selectComment(){
Optional<Comment> byId = commentRepository.findById(1);
System.out.println(byId.get());
}
그래서 my batis 를 사용 하지 않 으 려 면 springboot 통합 jpa 도 좋 은 선택 이다.
redis 사용
위 에 서 는 my batis 든 springdatajpa 든 모두 관계 형 데이터 베 이 스 를 바탕 으로 작 동 합 니 다.우리 가 위 에서 작 동 하 는 것 은 my sql 데이터 베 이 스 를 조작 하 는 것 입 니 다.현재 redis 도 프로젝트 에서 자주 사용 되 고 있 으 며,springboot 통합 사용 redis 도 편리 합 니 다.
도입 의존
마찬가지 로 우 리 는 우선 의존 을 도입 해 야 한다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
redis 연결 정보 설정application.propertis 에 redis 설정 추가
#redis
spring.redis.host=127.0.0.1
#redis
spring.redis.port=6379
#redis
spring.redis.password=
사실 지금까지 우 리 는 프로젝트 에서 redis 데이터 베 이 스 를 조작 할 수 있 도록 통합 되 었 다.삽입 과 찾기 를 위 한 테스트 방법 을 쓰 겠 습 니 다.
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void insert(){
redisTemplate.opsForValue().set("quellanan"," ");
}
@Test
public void select(){
String quellanan = redisTemplate.opsForValue().get("quellanan");
System.out.println(quellanan);
}
우리 가 직접 사용 하 는 String RedisTemplate 를 볼 수 있 습 니 다.이것 은 JdbcTemplate 에서 데이터 베 이 스 를 조작 하 는 것 과 같다.얘 들 아,이제 알 겠 지?my batis 나 jpa 라 는 프레임 워 크 를 사용 하지 않 고 간단 하고 거 친 조작 데이터 베 이 스 를 사용 한 셈 이다.
현재 많은 회사 들 이 데이터 베 이 스 를 사용 하 는 것 도 String RedisTemplate 나 RedisTemplate 를 직접 사용 하 는 redis 데이터 베 이 스 를 사용 하고 있 습 니 다.redis 기반 의 영구적 인 프레임 워 크 가 아직 유행 하지 않 기 때 문 입 니 다.물론 우리 도 사용 할 수 있 습 니 다.다음은 우리 가 좀 소란 을 피 울 게 요.
실체 클래스 를 만 듭 니 다.
@RedisHash(value = "persons") // redis
public class Person {
@Id // hashkey id
private String id;
@Indexed // redis
private String firstname;
@Indexed
private String lastname;
private Address address;
}
@RedisHash 는 클래스 의 저장 형식 을 지정 하 는 데 사 용 됩 니 다.여기 서 사용 하 는 것 은 RedisHash 가 데이터베이스 에 hash 저장 소 를 사용 하 는 것 을 표시 합 니 다.주의해 야 할 것 은@RedisHash 라 는 주해 만 실체 류 에 작용 합 니 다.이 persons 는 폴 더,key 의 접두사 와 같 습 니 다.@Id 는 메 인 키 를 표시 합 니 다.사실은 redis 에서 hash 구조 와 접두사 구성 key 입 니 다.
@Indexed,redis 데이터 베 이 스 를 표시 하여 2 급 색인 을 만 들 고 조건 조회 에 편리 하 며 접두사 와 속성 명 으로 key 를 구성 합 니 다.
인 터 페 이 스 를 만 듭 니 다.
이곳 에서 물 려 받 은 것 은 Crud Repository 입 니 다.또한 jpa 패 러 다 임 을 바탕 으로 관심 있 는 것 도 해 볼 수 있 습 니 다.
public interface PersonRepository extends CrudRepository<Person, String> {
//
List<Person> findByAddress_City(String name);
}
시험 방법.우 리 는 이어서 테스트 방법 을 하나 쓴다.
@Autowired
private PersonRepository personRepository;
@Test
public void savePerson(){
Person person = new Person();
person.setFirstname(" ");
person.setLastname(" ");
Address address = new Address();
address.setCity(" ");
address.setCountry(" ");
person.setAddress(address);
// redis
personRepository.save(person);
}
@Test
public void selectPerson(){
List<Person> list = personRepository.findByAddress_City(" ");
for (Person person : list) {
System.out.println(person);
}
}
redis 데이터 베 이 스 를 보고 있 습 니 다.
보고 있 습 니 다.이 키 들 은 어떤 종류의 저장 소 입 니까?key 를 제외 하고 persons:916 b5570-5c7f-4a96-b25f-98c9a2f1f43e 는 hash 이 고 나머지 는 set 입 니 다.
우리 가 만 든 색인 은 모두 set 로 저장 되 고 이 색인 들 은 key 값 만 저장 되 어 있 습 니 다.즉,우리 가 진정 으로 데 이 터 를 저장 하 는 곳 입 니 다.
한편,persons:916 b5570-5c7f-4a96-b25f-98c9a2f1f43e:idx 는 다른 색인 키 를 저장 합 니 다.
이렇게 하면 우 리 는 jpa 라 는 조작,특히 비교적 책임감 있 는 대상 을 통 해 우리 도 잘 처리 할 수 있다.
총결산
여기까지 입 니 다.spring boot 에서 my batis,spring data jpa,redis 를 어떻게 사용 하 는 지 알 면 됩 니 다.
springboot 통합 Mybatis,JPA,Redis 의 예제 코드 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 springboot 통합 Mybatis,JPA,Redis 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin Springboot -- 파트 14 사용 사례 REST로 전환하여 POST로 JSON으로 전환前回 前回 前回 記事 の は は で で で で で で を 使っ 使っ 使っ て て て て て リクエスト を を 受け取り 、 reqeustbody で 、 その リクエスト の ボディ ボディ を を 受け取り 、 関数 内部 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.