개요
오늘날 대부분의 인터넷 응용 프로그램은 여전히 mybatis를 사용하여 데이터베이스를 작동합니다. 이 기사는 Spring Boot에서 mybatis를 통합하는 방법을 소개합니다.
이전 기사는 Spring Boot에서 Jar와 직접 프로젝트를 실행하는 방법을 소개합니다. 필요한 경우 클릭하여 볼 수 있습니다.
스프링 부트 프로젝트를 만듭니다
Spring Boot Opening- 기사 작성 및 실행에는 Spring Boot 구성 요소를 사용하여 프로젝트를 만드는 방법을 설명하는 섹션이 있습니다. mybatis를 통합하려면 MySQL과 Mybatis의 두 구성 요소 만 확인하면됩니다.
물론이 메소드없이 POM.XML 파일에 직접 종속성을 추가 할 수도 있습니다. POM.XML 파일에서 의존성을 직접 추가하기로 결정했습니다.
종속성> <groupid> org.mybatis.spring.boot </groupid> <artifactid> mybatis-spring-boot-starter </artifactid> <3.3 </dependency> <pectionement> <groupid> mysql </groupid> <trifactid> mysql-connector-java </artifactid> <버전> 5.1.34 </version> </dependency> <pectomency> <groupId> com.alibaba </groupId> <artifactid> druid </artifactid> <bersion> 1.1.7 </version> </dependency>
데이터 소스는 알리바바의 드루이드를 사용합니다. 완전한 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.xsd"> <modeversion> 4.0.0 </modelversion> <groupid> com.springboot </groupid> </artifactid> <버전> 0.0.1-snapShot </version> <packaging> jar </packaging> <name> 연구 </name> <description> 스프링 부츠를위한 데모 프로젝트 </descrip> <groupid> org.springframework.boot </groupid> <artifactid> 스프링-부트-스테이터 parent </artifactid> <version> 1.10.10.10. 저장소의 부모-> </parent> <properties> <proffect.build.build.sourceencoding> utf-8 </project.build.sourceencoding> <proffess.reporting.outputencoding> utf-8 </project.reporting.outputencoding> <java.version> 1.8 </java.version> version> </justies> </java. <groupid> org.mybatis.spring.boot </groupid> <artifactid> mybatis-spring-boot-starter </artifactid> <3.1 </dependency> <pelection> <groupid> org.springframework.boot </groupId> <artifactid> spring-webb </artifactid> <pectionency> <groupId> mySQL </groupId> <artifactID> mySQL-connector-java </artifactid> <버전> 5.1.34 </version> </dependency> <prectionency> <groupId> com.alibaba </groupid> <artifactid> druid </excendency> 1.1.7 </version> 1.1.7 </version> 1.1.7 <groupid> com.alibaba </groupid> <artifactid> fastjson </artifactid> <2.45 </dependency> <pectionency> <groupid> org.spramframework.boot </groupid> <artifactid> spring-boot-starter-test </inpopact> </scope> </scope> </scope> </scope> </scope> <플러그인> <groupid> org.springframework.boot </groupid> <artifactid> Spring-Boot-Maven-Plugin </artifactid> </plugin> </plugins> </build> </project>
테이블을 만듭니다
테이블 작성`user` (`id` bigint (20)은 unull auto_increment,`name` varchar (30) not null default ', 기본 키 (`id`))))) 엔진 = innodb auto_increment = 8 기본 charset = utf8 댓글 ='사용자 정보 ';
엔티티를 만듭니다
패키지 com.springboot.entity; public class user {private long id; 개인 문자열 이름; public long getid () {return id; } public void setId (long id) {this.id = id; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } @override public String toString () {return "user {" + "id =" + id + ", name = ' + name +'/'' + '}'; }}MyBatis 매핑 파일 및 repo를 만듭니다
userrepo.java
package com.springboot.repo; import com.springboot.entity.user; import org.apache.ibatis.annotations.mapper; import org.spramework.stereotyp.component; import java.util.list;@compperpublic interface userRepo {int insert (사용자); 사용자 selectByPrimaryKey (긴 ID); int updateByPrimaryKey (사용자 사용자); int deletebyprimarykey (긴 ID); List <user> selectall ();}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.srespoor. <resultmap id = "baseresultmap"type = "com.springboot.entity.user"> <id column = "id"property = "id"property = "id"jdbctype = "bigint" /> <result column = "name"property = "name"jdbctype = "varchar" /> < /resultmap> <sql id = < /s id> < /s id> id = "selectByPrimaryKey"resultMap = "BaserEsultMap"ParameterType = "java.lang.long"> select <refid includ refid = "base_column_list" /> usher id = #{id, jdbctype = bigint} < /select> < /select <select "> selectmap" "selectmap" refid = "base_column_list"/>에서 </select> <update id = "updatebyPrimaryKey"ParameterType = "com.springboot.entity.user"> Update User <set> <if test = "name! = null">`name` = #{name, jdbctype = varchar}, </if> </if> #{id, jdbctype = bigint} </update> <delete id = "deletebyprimarykey"parametertype = "java.lang.long"> id = #{ #{id, jdbctype = big} </delete> <insert "insert"parametertype = "com.sproot. useGeneratedKeys = "true"keyProperty = "id"> 사용자에 삽입 <trim prefix = "("puffix = ")"suffixoverrides = ","> name </trim> <trim prefix = "values ("publix = ")"suffixoverrides = ","> #{name, jdbctype = varchar} </trim> </inft> </inft> </inft>application.properties를 작성하십시오
Spring Boot에서 생성 한 Application.properties 파일에 다음을 추가하십시오.
spring.datasource.name = spring_boot_study spring.datasource.url = jdbc : mysql : // localhost : 3306/test spring.datasource.username = root spring.datasource.password = xxxxxx spring.datasource.driverclass-name = com.jdbc.driver spring.datasource.type = com.alibaba.druid.pool.druiddatasource mybatis.mapper-locations = classpath : mapper/*. xml mybatis.type-aliases-package = com.springboot.entity
단위 테스트
패키지 com.springboot; import com.springboot.entity.user; import com.springboot.repo.userrepo; import org.junit.test; import org.junit.runner.runwith; import org.spramework.beans.beans.annotation.autowired; org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; import java.util.list; @runwith (springrunner.class) @springboottestpublic class {@autowired private userepo -userepofo userepopo; @test public void testinsert () {user user = new user (); user.setName ( "test2"); userrepo.insert (사용자); } @test public void testupdate () {user user = new user (); user.setid (6L); user.setName ( "test3"); userrepo.updatebyprimarykey (사용자); } @test public void testDelete () {userRepo.deleteByPrimaryKey (6L); } @test public void testelectbyPrimaryKey () {user user = userrepo.selectByPrimaryKey (7L); System.out.println (사용자); } @test public void testelectall () {list <user> userList = userRepo.Selectall (); System.out.println (UserList); }}요약
위는 Spring Boot Integration MyBatis의 예제 코드 (단순화 된 버전)입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!