Интеграция с Spring3
В качестве основной структуры пружина может интегрировать задние рамки, такие как Hibernate, Mybatis и т. Д.
Предыдущая статья представляет использование только Mybatis, а общая логика:
SQLSessionFactory <- файл конфигурации (включая конфигурацию подключения к базе данных)
Ixxxmapper <- sqlsession <- sqlSessionFactory
<- Интерфейс Mapper <- mapper xml
После получения ixxmapper вы можете вызвать его метод взаимодействия данных.
При интеграции с пружиной вышеуказанные объекты необходимо управлять как бобы:
DataSource Bean <- Конфигурация подключения к базе данных
SQLSessionFactory Bean <- DataSource
<- Файл конфигурации
Usermapper Bean <- sqlSessionFactory
<- Интерфейс Mapper
1. Добавьте зависимости в pom.xml:
<properties> <mybatis.spring.version> 1.2.1 </mybatis.spring.version> <dbcp.version> 1.4 </dbcp.version> <Spring.version> 3.1.2.release </spring.version> </properties> <Зависимости> <Зависимость> <! <groupId> org.mybatis </GroupId> <ArtifactId> mybatis-spring </artifactid> <serse> $ {mybatis.spring.version} </version> </depertive> <dependency> <!-Spring Context использует Spring-jdbc для подключения к Database-> <groupid> org.springframe <// <artifactid> spring-jdbc </artifactid> <sersive> $ {spring.version} </version> </dependency> <DepeCted> <!-DataSource-это экземпляр BasicDatasource-> <groupId> Commons-dbcp </GroupId> <TrifactId> Commons-dbcp </artifactid> <serse> $ {dbcp. </depertive> <depervice> <groupid> org.springframework </groupid> <artifactid> spring-test </artifactid> <sersion> $ {Spring.version} </version> </dependency> </depertion> 2. Создайте файл Beans-DA.xml под пансией Classpath:
<? xml version = "1.0" Encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id = "dataSource"> <!-DataBase Connection Bean-> <fthips name name ". value = "com.mysql.jdbc.driver" /> <name = "url" value = "jdbc: mysql: // localhost: 3306 /hbatis? Характерподинг = utf8" /> <name = "username" value = "root" /> name = "password". id = "sqlSessionFactory"> <!-sqlSessionFactory Bean-> <name = "dataSource" ref = "dataSource" /> <!-источник данных-> <name = "configlocation" value = "classpath: configuration.xml" /> <!-Файл конфигурации-> < /bean> <bean id = "usermapper" /> <! name = "sqlSessionFactory" ref = "sqlSessionFactory" /> <name = "mapperInterface" value = "com.john.hbatis.mapper.iusermapper" /> <!-Интерфейс отображения-> < /beans>
3. Испытательный класс:
@ContextConfiguration (locations = {"classPath: Beans-da.xml"}) открытый класс SpringInteGrationTest Extavends AbstractTestngSpringContextTests {Private Static Final Log = loggerFactory.getLogger (SpringInteGrationTest.class); @Resource iusermapper Mapper; @Test public void QueryTest () {user user = mappper.getuserbyid (1); log.info ("name: {}, адрес: {}", user.getName (), user.getAddress ()); }} Интеграция с Springmvc
Здесь мы опираемся на интеграцию с Spring3:
1. Добавьте зависимости Springmvc и Freemarker в pom.xml:
<properties> <freemarker.version> 2.3.19 </freemarker.version> <servlet.version> 2.5 </servlet.version> </Свойства> <Depertiency> <groupid> org.freemarker </GroupId> <strifactid> freemarker </artifactid> <version> $ {freemarker. <//artifactid> <version> $ {freemarker. <depervice> <groupid> javax.servlet </groupid> <artifactid> Servlet-Api </artifactid> <serse> $ {servlet.version} </version> <cracpe>2. Добавьте Spring's Sulderer и Springmvc Servlet в web.xml:
<Learser> <lloader-class> org.springframework.web.context.contextloaderListener </stirler-class> <!-Слушайте события контейнеров, инициализируйте и закрывают контекст веб-приложения и позвоните в ContextCleanuplieNerener для очистки ресурсов-> </reluess> <dellocer> <lloader-class> org.springframework.web.context.contextCleanuplistener </sluster-class> <!-Очистка связанных с воспроизводственными ресурсами в ServletContext, когда веб-приложение будет закрыто-> </Helloer> <Servlet> <Servlet-name> HBATIS </servlet-name> <Servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <!-<init-param> <param-name> contextConfiglocation </param-name> <value>/web-inf/hbatis-servlet.xml </param-value> </init-param> not villy-will will-will will will will will will will will will will will will will will will will will will will will. $ {project.name} -servlet.xml в каталоге Web-Inf-> <Load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name> hbatis </servlet-name> <url-pattern>*.3. Создайте новый под Web-Inf:
Файл конфигурации Spring ApplicationContext.xml:
<? xml version = "1.0" Encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: p = "http://www.springframework.org/schema/p" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://wwww.spramema http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> location = "classpath: /database.properties" /> <!-Файл конфигурации базы данных-> <Bean Id = "DataSource" P: DriverClassName = "$ {DriverClassName}" p: url = "$ {url}" p: username = "$ {user_name}" p: password = "$ {password}"! <bean id = "sqlSessionFactory"> <!-sqlSessionFactory Object-> <name = "dataSource" ref = "dataSource" /> <!-Источник данных-> <name = "configlocation" value = "classpath: configuration.xml" /> <!-файл конфигурации mybatis-> <! value = "classpath*: com/john/hbatis/model/*. xml"/>-> <!-Вы можете настроить файл отображения в configururation.xml или здесь, но у вас не может быть параметрической, результатов, SQL и т. Д. С тем же идентификатором-> </bean> <bean id = "mapperconfigur name = "basepackage" value = "com.john.hbatis.mapper"/> </bean> </beans>База данных.
DriverClassName = com.mysql.jdbc.driver url = jdbc: mysql: // localhost: 3306/myBatis?
ПРИМЕЧАНИЕ. Поскольку MapperScannerConfigurer может привести к тому, что имя пользователя принесет учетную запись пользователя, что приводит к сбою подключения к базе данных, поэтому оно изменяется на другое значение: user_name.
Файл конфигурации Springmvc Hbatis-servlet.xml:
<? xml version = "1.0" Encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation = "http://wwww.spramemema. http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd " RequestMappingHandlermapping, requestMappingHandlerAdapter и ExcementHandLerexceptionResolver для предоставления поддержки для аннотаций, таких как @Requestmapping, @ExceptionHandler и т. Д.-> <Контекст: компонент-сканирование Base-package = "com.john.hbatis.controller" /> <!-сканирование класса с определенными аннотациями в разделе «Утверждение» и «Вседство». Просмотр процессора-> <bean id = "viewResolverftl"> <name = "viewClass" value = "org.springframework.web.servlet.view.freemarker.freemarkerview"/> <name = "contentType" value = "text/html; charset = utf -8"/> <properation = "value =" text/html; charset = utf-8 "/> <frovestive =" name = "cache" value = "false"/> <name = "viewNames"> <Array> <dall>*. ftl </value> </array> </property> <!-<name = "suffix" value = ". ftl"/>-> <Свойство = "Порядок" value = "0"/> <! id = "freemarkerconfig"> <property name = "templateLoaderPaths"> <sist> <value>/web-inf/ftl/</value> <!-Путь загрузки шаблона-> </list> </properation> </bean> </beans>
4. MVC:
Управляющий слой: usercontroller.java
@Controller @Requestmapping ("/article") открытый класс usercontroller {@autowired iusermapper mapper; @Requestmapping ("/list") public String Showall (ModelMap ModelMap) {list <статья> articles = mappper.getarticlicsbyuserid (1); modelmap.addattribute («Статьи», статьи); вернуть "main.ftl"; }}Просмотр слоя: main.ftl:
<#List статьи как статья> <div> $ {article.id}. $ {article.title}: $ {article.content} </div> </#list>5. Начните проект и введите браузер: http: // localhost: 8080/hbatis/article/list.htm, чтобы просмотреть результаты.