Spring+SpringMVC+Mybatis+mysql整合详解

5 篇文章 0 订阅
3 篇文章 0 订阅

Spring+SpringMVC+Mybatis+mysql整合详解

1)  整体架构


1)  jar包



3) 具体代码实现

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">

<!-- 直接写成dao层接口 -->

<!--parameterType="int" 是参数类型,比如之前我们的“public void delete(int id);同理resultType为返回值类型-->

<mapper namespace="com.amaker.dao.UserDao">

    <select id="getUser" resultType="com.amaker.bean.User">

        select * from user

    </select>

    

    <select id="getOne" parameterType="int" resultType="com.amaker.bean.User">

        select * from user where id=#{id}

    </select>

    

    <insert id="insertUser" parameterType="com.amaker.bean.User">

        Insert into user(name,password,type,money) value(#{name},#{password},#{type},#{money})

    </insert>

    

    <update id="updateUser" parameterType="com.amaker.bean.User">

        update user set name=#{name},password=#{password},type=#{type},money=#{money} where id=#{id}

    </update>

    

    <delete id="deleteUser" parameterType="int">

        delete from user where id=#{id}

    </delete>

</mapper>


hello-mybatis.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"

xmlns:jdbc="http://www.springframework.org/schema/jdbc"

xmlns:jee="http://www.springframework.org/schema/jee"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/beans

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/spring-mvc.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd">

 

    

     <!-- 自动扫描 -->  

    <context:component-scan base-package="com.amaker" />  

  

  <!-- 引入配置文件 -->  

    <bean id="propertyConfigurer"  

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

        <property name="location" value="classpath:jdbc.properties" />  

    </bean>  

  

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  

        destroy-method="close">  

        <property name="driverClassName" value="${driver}" />  

        <property name="url" value="${url}" />  

        <property name="username" value="${username}" />  

        <property name="password" value="${password}" />  

        

        <!-- 配置连接池的初始值 -->

        <property name="initialSize" value="1" />

        <!-- 连接池的最大值 -->

        <!-- <property name="maxActive" value="500"/> -->

        <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 -->

        <!-- <property name="maxIdle" value="2"/> -->

        <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 -->

        <property name="minIdle" value="1" />

        <property name="maxActive" value="100" />

        <property name="maxIdle" value="20" />

        <property name="maxWait" value="1000" /> 

    </bean>  

    

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  

        <property name="dataSource" ref="dataSource" />  

        <!-- 自动扫描mapping.xml文件 -->  

        <property name="mapperLocations" value="classpath:com/amaker/mapping/*.xml"></property>  

    </bean>  

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

<constructor-arg ref="sqlSessionFactory" />

</bean>

  

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  

        <property name="basePackage" value="com.amaker.*" />  

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  

    </bean>  

  

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  

    <bean id="transactionManager"  

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  

        <property name="dataSource" ref="dataSource" />  

    </bean>  

    

    <!-- 通知 -->

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <!-- 传播行为 -->

            <tx:method name="save*" propagation="REQUIRED"/>

            <tx:method name="insert*" propagation="REQUIRED"/>

            <tx:method name="update*" propagation="REQUIRED"/>

            <tx:method name="delete*" propagation="REQUIRED"/>

            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>

            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>

             <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>

        </tx:attributes>

    </tx:advice>

</beans>


jdbc.properties

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mybatis_shop

username=root

password=

hello-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://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd

        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">


      <!-- 开启注解 -->

      <mvc:annotation-driven/>

      <!-- 设置组件扫描的基础包controller包 -->

      <context:component-scan base-package="com.amaker.bean"/>

      

      <!-- 配置视图解析器 -->

      <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">

          <property name="prefix" value="/WEB-INF/jsp/" />

          <property name="suffix" value=".jsp" />

      </bean>

</beans>


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">

 

  <!-- 配置DispatcherServlet -->

  <servlet>

     <servlet-name>hello</servlet-name>

     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

  </servlet>

  <servlet-mapping>

     <servlet-name>hello</servlet-name>

     <url-pattern>/</url-pattern>

  </servlet-mapping>

  

 

  <!-- Spring 的监听器可以通过这个上下文参数来获取school-mybatis.xml的位置 -->

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>classpath:hello-mybatis.xml</param-value>   

  </context-param>

  

    <!-- 创建Spring的监听器 -->

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

  <!-- 创建字符过滤器 -->

  <filter>

     <filter-name>CharacterFilter</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>CharacterFilter</filter-name>

      <url-pattern>/*</url-pattern>

  </filter-mapping>

</web-app>



User.java


package com.amaker.bean;

public class User {

private int id;

private String name;

private String password;

private int type;

private float money;

public User() {

super();

}

public User(int id, String name, String password, int type, float money) {

super();

this.id = id;

this.name = name;

this.password = password;

this.type = type;

this.money = money;

}


public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

public int getType() {

return type;

}

public void setType(int type) {

this.type = type;

}

public float getMoney() {

return money;

}

public void setMoney(float money) {

this.money = money;

}

}

UserDao.java

package com.amaker.dao;

import java.util.List;


import com.amaker.bean.User;


public interface UserDao {

 //查询

public List<User> getUser() throws Exception;

//查询个人

public User getOne(int id) throws Exception;

//插入

public void insertUser(User user) throws Exception;

//修改

public void updateUser(User user) throws Exception;

//删除

public void deleteUser(int id) throws Exception;

}


UserDaoImpl.java

package com.amaker.daoimpl;

import java.util.List;


import javax.annotation.Resource;


import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import org.springframework.stereotype.Repository;


import com.amaker.bean.User;

import com.amaker.dao.*;

@Repository

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{


@Resource

    public void setSuperSessionFactory(SqlSessionFactory sessionFactory){

        this.setSqlSessionFactory(sessionFactory);

    }

//查询

@Override

public List<User> getUser() throws Exception {

// TODO Auto-generated method stub

return this.getSqlSession().selectList("com.amaker.dao.UserDao.getUser",null);

}

//添加

@Override

public void insertUser(User user) throws Exception {


this.getSqlSession().insert("com.amaker.dao.UserDao.insertUser", user);

}

//修改

@Override

public void updateUser(User user) throws Exception {

this.getSqlSession().update("com.amaker.dao.UserDao.updateUser",user);

}

//查询个人

@Override

    public User getOne(int id) throws Exception {

// TODO Auto-generated method stub

return this.getSqlSession().selectOne("com.amaker.dao.UserDao.getOne", new Integer(id));

}

//删除

@Override

    public void deleteUser(int id) throws Exception {

 this.getSqlSession().delete("com.amaker.dao.UserDao.deleteUser", new Integer(id));

    }

}


UserService.java

package com.amaker.service;


import java.util.List;


import com.amaker.bean.User;


public interface UserService {

//查询

public List<User> getUser ();

//查询个人

public User getOne(int id);

//插入

public void insertUser(User user);

//修改

public void updateUser(User user);

//删除

public void deleteUser(int id);

}

package com.amaker.service;


import java.util.List;


import javax.annotation.Resource;


import org.mybatis.spring.SqlSessionTemplate;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import com.amaker.bean.User;

import com.amaker.dao.UserDao;


@Service

@Transactional

public class UserServiceImpl implements UserService{

@Resource

private UserDao userDao;

//查询

public List<User> getUser(){

try {

return userDao.getUser();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}

//添加

@Override

public void insertUser(User user) {

try {

userDao.insertUser(user);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//修改

@Override

public void updateUser(User user) {

try {

userDao.updateUser(user);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//查询个人

@Override

public User getOne(int id) {

try {

return userDao.getOne(id);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}

//删除

@Override

public void deleteUser(int id) {

   try {

userDao.deleteUser(id);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


add.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert title here</title>

</head>

<body>

<form method="post" modelAttribute="user">

  name:<input type="text" name="name"><br><br>

  password:<input type="password" name="password"><br><br>

  type:<input type="text" name="type"><br><br>

  money:<input type="text" name="money"><br><br>

  <input type="submit" value="确定"/>

  <input type="reset" value="重置"/>

</form>

</body>

</html>


success.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert title here</title>

</head>

<body>

<c:forEach var="user" items="${users }">

${user.id }--${user.name }--${user.password }--${user.type }--${user.money }--<a href="http://localhost:8080/SpringMVC_Mybatis/ooo/deleteUser/${user.id}">>删除</a><br>

</c:forEach>

<br>

<a href="http://localhost:8080/SpringMVC_Mybatis/ooo/insert">>add</a><br>

<a href="http://localhost:8080/SpringMVC_Mybatis/ooo/updateUser">>updateUser</a>

</body>

</html>


update.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"

    pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Insert title here</title>

</head>

<body>

<form method="post" modelAttribute="user">

  id:<input type="text" name="id"><br><br>

  name:<input type="text" name="name"><br><br>

  password:<input type="password" name="password"><br><br>

  type:<input type="text" name="type"><br><br>

  money:<input type="text" name="money"><br><br>

  <input type="submit" value="确定"/>

  <input type="reset" value="重置"/>

</form>

</body>

</html>


数据库:




整体效果


add效果


点击确定后


UpdateUser效果



确定之后


点击删除效果后


整合面临到的问题解决最久的:

1)      Context initialization failedorg.springframework.beans.factory.BeanDefinitionStoreException:Failed to read candidate component class: file[E:\JEE\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVC_Mybatis\WEB-INF\classes\com\amaker\bean\User.class];nested exception is java.lang.IllegalArgumentException

解决方法:换jdk版本,一开始tomcat7+jdk1.8后改为tomact7+jdk1.7,得到解决!



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值