Springmvcとmybatisの統合(注)

データベースの準備

mysql> CREATE DATABASE IF NOT EXISTS test_db_char
    -> DEFAULT CHARACTER SET utf8
    -> DEFAULT COLLATE utf8_chinese_ci;
create table menu(
id int primary key ,
name varchar(20),
pid int
)

insert into menu values(1,'系统设置',0);
insert into menu values(2,'销售管理',0);
insert into menu values(3,'修改密码',1);
insert into menu values(4,'添加用户',1);
insert into menu values(5,'销售人员新增',2);
insert into menu values(6,'删除销售人员',2);


データベースのリモート接続を開きますデータベース接続構成:https://blog.csdn.net/isomebody/article/details/73012417ダウンロードドライバー
eclipse MySQLJDBCドライバーをインポートしてデータベースをJavaで操作する方法

jarをインポート

1. web.xmlを構成します:リスナー、コントローラー、およびコンテキストパラメーターを構成します

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

<!-- Spring的监听器和上下文参数 --> 
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 监听器 -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
 <!-- SpringMVC前端控制器 -->
  <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup><!-- Tomcat启动,该类被加载 -->
  </servlet>
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
  
  <!-- 字符编码过滤器 -->
  <filter>
  <filter-name>encoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

2.applicationContext.xml:mybatisを構成します

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans.xsd 
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop.xsd
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context.xsd 
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">

<!--扫描service包-->
<context:component-scan base-package="com.service.impl"></context:component-scan>
<!--加载属性文件  并  创建数据源连接池-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value=""></property>
</bean>

<!-- Spring 整合mybatis -->
<!--创建mybatis的SqlSessionFactory工厂类对象-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--mybatis-spring-1.2.2  -->
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.pojo"></property> <!-- <resultMap type="menu" id="mymap">类型别名,对包下的类起个别名 -->
</bean>

<!--扫描器:配置扫描mybatis的dao接口 ,会为dao接口创建myabtis的dao接口实现类对象,放置到session工厂中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.bjsxt.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="factory"></property>
</bean>



<!--声明spring 的事物管理器对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--声明以注解的方式配置spring 的事物-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <tx:attributes>
   <tx:method name="ins*"/>
   <tx:method name="del*"/>
   <tx:method name="upd*"/>
   <tx:method name="*" read-only="true"/>
   </tx:attributes>
</tx:advice>


<!-- 配置aop-Aspect Oriented Programming -->
<aop:config>
<aop:pointcut  expression="execution(* com.bjsxt.service.impl.*.*(..))" id="mypointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/>
</aop:config>


</beans>
jdbc.properties

sqlserver接続構成:

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost;DatabaseName=[read]
jdbc.username=sa
jdbc.password=

mysql接続構成:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/read
jdbc.username=root
jdbc.password=

3.springmvc.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://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.1.xsd 
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
    <!-- 注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!-- 静态资源不拦截配置                                                     请求格式:*表示所有文件,**表示所有文件及子文件-->
    <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    
    
    <!-- 视图解析器 -->
    <bean id="vierResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"></property>
    <property name="suffix" value=".jsp"></property>
    </bean>
    </beans>

POJO(Plain Ordinary Java Object)の単純なJavaオブジェクトは、実際には通常のJavaBeanであり、EJBとの混同を避けるために作成された省略形です。
メニューデータベースの属性に加えて、対応するgetメソッドとsetメソッド

コントローラーコード:

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pojo.Menu;
import com.service.MenuService;


@Controller
public class MenuController {
    
    
	
	/*Springmvc容器调用Spring容器中内容*/
	@Resource
	private MenuService menuServiceImpl;/*@Resource默认是byname注入,名字不同会根据类别*/
	
	
	@RequestMapping("show")
	@ResponseBody
    public List<Menu> show(){
    
    
		System.out.println("show");
		return menuServiceImpl.show();
		}
    
    
}

Mybatisデータベースのものと同じパスの下の構成

import java.util.List;

import com.pojo.Menu;

public interface MenuMapper {
    
    
    List<Menu> selBypid(int pid);
}

MenuMapper.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.bjsxt.mapper.MenuMapper">
  <resultMap type="menu" id="mymap">
      <id property="id" column="id"/>
      <collection property="children" select="com.bjsxt.mapper.MenuMapper.selBypid" column="id"></collection>
  </resultMap>
  <select id="selBypid" parameterType="int" resultMap="mymap">
     select * from menu where pid=#{0}
  </select>
</mapper>

実行時に呼び出されるメソッド

インターフェイスと実装クラスは自動的にSpringコンテナに登録されます

public interface MenuService {
    
    

	List<Menu> show();
}
@Service
public class MenuServiceImpl implements MenuService{
    
    
    @Resource
	private MenuMapper meunMapper;
	
	@Override
	public List<Menu> show() {
    
    
		// TODO Auto-generated method stub
		
		return meunMapper.selBypid(0);
	}

}

プロセスの呼び出し:show-> controler-> MenuServiceImpl-> meunMapper-> mybatis


@ RequestParam、@ ResponseBody使用
@Serviceアノテーション使用

おすすめ

転載: blog.csdn.net/ResumeProject/article/details/113575636
おすすめ