설명
이 프로젝트는 Maven 구조를 채택하는데,이 구조는 주로 Spring MVC + Mybatis, 컨트롤러를 보여주고 데이터를 얻고 데이터를 JSON 형식으로 반환합니다.
프로젝트 구조
패키지 의존성 및 지침
POM 파일 :
<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/0.0.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <<1modelversion>4.0.0</modelversion> groupid>com.hbb0b0.maven01</gro upid> <artifactid> maven01 </artifactid> <packaging> war </packaging> <snapshot </version> <name> maven01 Maven WebApp </name> <url> http://maven.apache.org </url> <properties> <!-mybatis 버전 번호-> <mybatis.version> 3.2.6 </mybatis.version> <!-log4J 로그 파일 관리 패키지 버전-> <slf4j.version> 1.7.7 </slf4j.version> <log4j.version> 1.2.17 </log4j.version> </properties> <pectionements> <groupid> junit </groupid> <artifactid> junit </artifactid> <vers ION> 3.8.1 </version> <Scope> 테스트 </scope> </fectionency> <pectient> <groupId> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> <버전> 4.1.2. release </version> </dependency> <!- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl-> <groupid> org.codehaus.jackson </groupid> <artifactid> Jackson-mapper-asl </artifactid> <9.2 </dependence> <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl-> <groupid> org.codehaus.jackson </groupid> <artifactid> Jackson-core-asl </artifactid> <9.13 </dependency> <!--- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind-> <groupid> com.fasterxml.jackson.core </groupid> <artifactid> Jackson-databind </artifactid> 2.9.3 </version> </dependency/spring 패키지 -> <pectionency> <groupId> org.mybatis </groupid> <artifactid> mybatis-spring </artifactid> <버전> 1.3.0 </version> </dependency> <!-MySQL 데이터베이스 링크 Jar 패키지-> <pectionency> <groupId> mySQL </groupId> <artifactID> mySQL-connector-java </artifactid> <bersion> 5.1.30 </version> </fectionency> <!-mybatis orm 프레임 워크-> <pectionency> <groupId> org.mybatis </groupid> <artifactid> mybatis </artifactid> <버전> 3.4.1 </version> </dependency> <prectionement> <groupId> org.springframework </groupid> <artifactid> smpr-tx </artifactid> <version> 4.1.2 e </version> </dependency> <pectinement> <groupId> org.springframework </groupid> <artifactid> spring-jdbc </artifactid> <bersion> 4.1.2.2
구성 지침
web.xml
<! docType Web-App Public "-// Sun Microsystems, Inc.//dtd 웹 응용 프로그램 2.3 // en" ""http://java.sun.com/web-app_2_3.dtd "> <web-App> <web-App> archeType가 웹 애플리케이션을 생성했습니다 </display-name>-SpringMvcditoperser의 설정을 구성합니다. 매핑-> <서블릿> <Servlet-name> SpringMvc </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-cla SS> <Init-Param> <Param-Name> ContextConfigLocation </param-name> <param-value>/web-inf/springmvc-servlet.xml </param-value> </init-param> <!- </load-on-startup> 1 </load-on-startup>-> </servlet> <servlet-mapping> <servlet-name> springmvc </servlet-name> <Url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Springmvc-servlet.xml
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/sprger--mvc-4.1.xdend 및 하위 패키지-> <context : component-scan base-package = "com.maven01.*" /> <!-정적 자원을 처리하지 마십시오-> <mvc : default-servlet handler /> <!-주석을 사용하는 경우 설정에 따라 구성해야합니다-> <mvc : Annotation-Driven />-Dispater servelet-> <mvc : mvc : resourt mapte = /*. location = "/static/"/> <!-InternalResourceViewResolver-> <!-주석을 사용하는 경우 다음 설정을 구성해야합니다.> <bean id = "Mapping JacksonHttPmessAgeConverter"class = "org.springframework.http.converter.json.mappingjackson2shtpmson2shtpmson2shtpmson2shtpmson2shtson2jjacks를 구성해야합니다. name = "supportedMediAtypes"> <slest> <alue> application/json; charset = utf-8 </value> </list> </property> </bean> <beanclass = "org.springframework.web.servlet.view.internalresourceviewresolver"id = <!-prefix-"> <- presourceview"> 이름 = "prefix"value = "/web-inf/view/"/> <!-접미어-> <property name = "plustix"value = ". jsp"/> </bean> <!-mysql-> <!-외부 데이터 소스 구성 정보를 소개합니다.> <beanclass = "org.springframework.beans.configer"> 이름 = "위치"> <value> classpath : jdbc.properties </value> </property> </bean> <!-데이터 소스 구성-> <bean id = "dataSource"class = "org.springframework.jdbc.datasource.driverManagerDatasource"> Property Name = "DriverCleassame" value = "$ {jdbc.driver}"> </property> <property name = "url"value = "$ {jdbc.url}"> </property name = "username"value = "$ {jdbc.username}"> </property> <!-Spring and MyBatis가 완벽하게 통합되어 있지 않습니다. id = "sqlsessionFactory"> <속성 이름 = "dataSource"ref = "dataSource"/> <!-자동으로 mapping.xml 파일-> <property name = "mapperlocations"value = "classpath : com/maven01/mapper/*. xml"> </bean> <! -> <bean> <property name = "basepackage"value = "com.maven01.dao"/> <property name = "sqlsessionfactorybeanname"value = "sqlsessionfactory"> </property> <!-트랜잭션 관리자 구성-> <bean id = "txmanager"class = "org.springframework.jdbc.datasource.datasourcetransactionManager"> <property name = "dataSource"ref = "dataSource"> </property> </bean> </beans>jdbc.propertiesjdbc.driver = com.mysql.jdbc.driverjdbc.url = jdbc : mysql : // localhost : 3306/Employeploins? useUnicode = true & characterEncoding = utf-8jdbc.username = rootjdbc.prassworda
mybatis 맵퍼 파일의 구성
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype mapper public "-// mybatis.org//dtd Mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <Mapper Namespace ="mapper namepace = < " id = "getall"resulttype = "com.maven01.pojo.employee"> 선택*Fromployeeslimit 1,10 </select> </mapper>
DB 구조
이 프로젝트는 MySQL 샘플 Employeees 데이터베이스를 사용하고 필요한 친구들이 직접 다운로드 할 수 있습니다.
http://www3.ntu.edu.sg/home/ehchua/programming/sql/sampledatabases.html
코드 설명
모델
package com.maven01.pojo; public class Employee {public int emp_no; public string first_name; public int getemp_no () {return emp_no;} public void setemp_no (int emp_no) {this.emp_no = emp_no;} public strest getfirst_name (}}}} first_name) {this.first_name = first_name;}}다오
package com.maven01.dao; import java.util.list; import org.springframework.stereotype.repository; import com.maven01.pojo.employee; public interface iemployeedao {public list <ceplyee> getall ();}서비스
패키지 com.maven01.service; import java.util.list; import com.maven01.pojo.employee; public interface iemployeeservice {public list <ployee> getall ();}ServiceMpl
패키지 com.maven01.service.impl; import java.util.list; import org.springframework.bean.beans.annotation.autowired; import org.springframework.stereotyp.service; import com.maven01.dao.iemployeedao; import com.maven01.pojo.mporee; com.maven01.service.*; import javax.annotation.resource; @servicepublic class EmployepiceImpl은 iemployeeservice {@autowiredprivate iemployeedao dao; public Employeeserviceimpl () {} public list <Employee> getall () {return dao.getall ();}};제어 장치
패키지 com.maven01.controller; import java.util.arraylist; import java.util.list; import javax.annotation.resource; import org.springframework.stereotyp.controller; import org.spramframework.web.bind.annotation.requestmapping; import; org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.responsebody; import com.maven01.dto.*; import com.maven01.pojo.employee; import com.maven01.service.iemployeeservice;@controller@requestmapping ( "/mvc") public class democontroller {@resourceprivate iemployeeservice EmployErvice; @requestMapping (method = requestmapping (method = requestmapping, value = "/getemployeelist", application/json). {return Employeeservice.getall ();}}실행 결과
이 프로젝트의 코드는 GIT에 제출되었으며 다운로드 주소는 https://github.com/hbb0b0/springmybatis.git입니다.
만난 함정 :
MapperscannerConfigurer는 DAO 레이어 만 포함하도록 구성되어 있습니다. 스캔 할 전체 패키지를 구성하지 마십시오. 그렇지 않으면 오류가 발생합니다.
<!-Spring은 DAO 인터페이스에서 클래스를 자동으로 찾을 것입니다-> <ean> <property name = "basePackage"value = "com.maven01.*"/> <property name = "sqlsessionfactorybeanname"value = "sqlsession eftory"> </property> </bean> org.springframework.bean.nounmipebeanneed incection : intecome. [com.maven01.service.iemployeeservice]가 정의되어 있습니다 : 예상 단일 일치 콩이지만 찾았지만 2 : Employeeserviceat org.springframework.beans.support.defaultlistablebeanctory.doresolvedependency (defaultlistablebeanfactory.java:1061) <! 스프링은 그 아래에서 클래스를 자동으로 찾습니다 -> <ean> <property name = "basepackage"value = "com.maven01.dao"/> <속성 이름 = "sqlsessionsictortorybeanname"value = "sqlsessionfactory"> </bean> </bean> </bean> </bean>
Mybatis 패키지의 일치는 Mybatis-Spring 및 Mybatis 및 Spring의 낮은 버전입니다.
java.lang.abstractmethoderror : org.mybatis.spring.transaction.springmanagedtransaction.gettimeout () l
요약
위는 편집자가 소개 한 스프링 MVC 조합 Mybatis 프레임 워크 예제에 대한 자세한 설명입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!