머리말
오늘, mybatis를 통합하는 SpringBoot에 대해 알아 보겠습니다. mybatis를 통합하는 두 가지 방법이 있습니다. 하나는 주석을 기반으로하고 다른 하나는 XML 구성을 기반으로합니다. 오늘, 먼저 주석 기반 Mybatis 통합에 대해 알아 봅시다. 나는 아래에서 많이 말하지 않을 것입니다. 자세한 소개를 살펴 보겠습니다.
그것은 mybatis이기 때문에 mybatis와 관련이 있어야하고 MySQL을 사용하므로 MySQL 관련을 소개해야합니다.
<!-https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-starter-> <pectionency> <groupid> org.mybatis.spring.boot </groupid> <artifactid> mybatis-spring-boot-starter </artifactid> </dependency> <!-https://mvnrepository.com/artifact/mysql/mysql-connector-java-> <pectionency> <groupid> mysql </groupid> <artifactid> mysql-connector-java </artifactid> version> 8.0.11 </dependency>
여기에서 사용자 모델이 작성되며 데이터베이스 테이블과 비교하기에 편리합니다. 여기에서 mybatis라는 데이터베이스가 MySQL에서 작성되었으며 사용자 테이블이 작성됩니다. 동시에, 열거 클래스 usersexenum이 생성됩니다.
테이블 생성`user` (`ID` int (11) NOT NULL AUTO_INCREMENT,`name` varchar (20) 기본 널,`age` int (11) 기본 널,`sex` varchar (20) 기본 널, 기본 키 (`id`)))) 엔진 = innodb auto_increment = 9 기본 charset = utf8;
package com.example.model; import java.io.serializable; 공개 클래스 사용자는 시리얼이즈 가능 {@override public string toString () {// todo 자동 생성 메소드 스텁 "user [id =" + id + ", name =" + name + ", age =" + age + "]; } public int getId () {return id; } public void setid (int id) {id = id; } public String getName () {return name; } public void setName (문자열 이름) {이름 = 이름; } public int getage () {반환 연령; } public void 설정 (int Age) {Age = Age; } private int id; 개인 문자열 이름; 사적인 int 연령; 개인 userExenum 섹스; 공개 사용자 exenum getsex () {return sex; } public void setSex (usersExenum 섹스) {섹스 = 섹스; }} package com.example.model; public enum usersexenum {man, woman}여기서는 모델을 데이터베이스를 작동하는 SQL과 비교해야합니다. 우리는 어떤 비교를 사용해야합니까? 그런 다음 매퍼를 만들어야합니다. 여기에는 추가, 삭제, 수정 및 검색이 있습니다.
package com.example.mapper; import java.util.list; import org.apache.ibatis.annotations.delete; import org.apache.ibatis.insert; import org.apache.ibatis.annotations.result; import org.apache.abatis.annotations.results; import org.apache.ibatis org.apache.ibatis.annotations.update; import com.example.model. * ;; public interface usermapper {@select ( "select * from user") @results ({@result (property = "sex", column = "sex", javatype = userexenum.class), @result (name = ")); @select ( "select *에서 선택 * id = #{id}") @Results ({@result (property = "sex", column = "sex", javatype = userexenum.class), @result (property = "name", "name ="name ")) user getone (int id); @Insert ( "사용자 (이름, 나이, 섹스) 값에 삽입 ( #{name}, #{age}, #{sex})") void insert (사용자 사용자); @update ( "사용자 세트 이름 =#{username}, age =#{age} 여기서 id =#{id}") void update (user user); @delete ( "id =#{id}"void delete (int id);}에서 삭제합니다.Mapper는 위에서 구성되어 있으므로 Mapper의 위치를 어떻게 알 수 있습니까? 따라서 @mapperscan에 주석이 있습니다.
package com.example.demo; import org.mybatis.spring.annotation.mapperscan; import org.springframework.boot.springApplication; import org.spramframewort.boot.autoconfigure.springbootapplication;@springbootapplication@mappsercan ( "com.mopport.") static void main (String [] args) {springApplication.run (demoapplication.class, args); }}여기에서 UserController가 생성되고 하나는 모든 사용자를 표시하고 다른 하나는 새 사용자를 추가 한 다음 모든 사용자를 표시하는 것입니다.
package com.example.demo; import java.util.list; import org.springframework.beans.beans.annotation.autowired; import org.spramework.stereotyp.controller; import org.springframework.ui.model; import org.springframework.web.bind.antation org.springframework.web.bind.annotation.requestmethod; import com.example.mapper.usermapper; import com.example.model.user; import com.example.model.usersexenum;@controller@requestmapping ( "/user") 공개 클래스 usercontroller {@autowired usermapperporper; @requestmapping (value = "/alluser.do",Method = requestMethod.get) public String getAllUsers (모델 모델) {list <user> users = usermapper.getall (); model.adtattribute ( "사용자", 사용자); "사용자리스트"를 반환합니다. } @requestmapping (value = "/insert.do",Method = requestMethod.get) public String addUser (모델 모델) {user user = new user (); user.setName ( "cuiyw"); user.setage (27); user.setsex (userexenum.man); usermapper.insert (사용자); List <user> user = usermapper.getall (); model.adtattribute ( "사용자", 사용자); "사용자리스트"를 반환합니다. }}매퍼와 모델도 위에 설정됩니다. 데이터베이스와 상호 작용하려면 데이터베이스 주소 및 기타 정보를 구성해야합니다. 예외는 Java.sql.sqlexception입니다. 서버 시간대 값 'Öð¹ú ± ê × ¼ ~ ± ¼ä'는 인식되지 않거나 하나 이상의 시간대를 나타냅니다. 시간대 지원을 활용하려면보다 구체적인 시간대 값을 사용하려면 서버 또는 JDBC 드라이버 (Servertimezone 구성 속성을 통해)를 구성해야합니다. 다음 시간 영역은 mySQL에서 설정됩니다. Global time_zone = '+8:00';
spring.mvc.view.prefix =/view/spring.mvc.view.view.suffix = .jspmybatis.type-aliases-package = com.example.modelspring.datasource.driverclassname = com.mysql.cj.jdbc.driverspring.datasource.url = jdbc : mysql : // localhost : 3306/mybatisspring.datasource.username = rootspring.datasource.password = 123456
7. 표시 할 페이지를 만듭니다
여기서는 이전 블로그에 따라 JSP를 사용하여 데이터를 표시합니다.
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8"%> <%@ taglib prefix = "c"uri = "http://java.sun.com/jsp/jstl/core"%> <! 4.01 전환 // en ""http://www.w3.org/tr/html4/loose.dtd"> html> http-equiv = "content-type"content = "text/html; <tr> <th> name </th> <th> age </th> <th> 성별 </th> </tr> <c : foreach items = "$ {users}"var = "item"> <tr> <td> $ {item.name} </td> <td> $ {item.age} </td> $ {item.sex} </td>} </c : foreach> </table> </body> </html>여기에서 먼저 http : // localhost : 8080/user/alluser.do 브라우저에서 사용자 목록을보고 http : // localhost : 8080/user/insert.do를 입력 할 수 있으며 목록에 추가 데이터 라인이 표시되는 것을 볼 수 있습니다.
mybatis의 주석 기반 통합을 사용하는 것이 더 쉽고 편리하지만 장점과 단점이 있습니다. 여러 테이블을 연결하는 것이 덜 편리 할 수 있으며 XML 기반 구성을 사용하는 것이 좋습니다.
좋아, 위는이 기사의 전체 내용입니다. 이 기사의 내용에 모든 사람의 연구 나 작업에 대한 특정 참조 가치가 있기를 바랍니다. 궁금한 점이 있으면 의사 소통을 위해 메시지를 남길 수 있습니다. Wulin.com을 지원 해주셔서 감사합니다.