springmvc+spring+mybatis 搭建

1、首先使用idea新建一個Maven webapp項目html

  

  

  

  

 

 

 

2、搭建目錄結構java

  

  我這裏列出的是搭建完了以後全部的目錄和文件,諸位先把目錄文件建起來,而後我在給出文件內容mysql

  

 

  這裏的目錄建好以後還須要設置一下,讓idea識別目錄做用,選擇File-Project Structureweb

  

  設置完成後okspring

3、配置文件內容sql

 

pom.xml數據庫

<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/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.test</groupId>
  <artifactId>ssm01</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>ssm01 Maven Webapp</name>
  <url>http://maven.apache.org</url>


  <properties>
    <!-- 設置項目編碼編碼 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- spring版本號 -->
    <spring.version>4.3.5.RELEASE</spring.version>
    <!-- mybatis版本號 -->
    <mybatis.version>3.4.1</mybatis.version>
  </properties>

  <dependencies>

    <!-- java ee -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>

    <!-- 單元測試 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- 實現slf4j接口並整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>


    <!-- 數據庫 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.41</version>
      <scope>runtime</scope>
    </dependency>

    <!-- 數據庫鏈接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <!-- mybatis/spring整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

  </dependencies>





  <build>
    <finalName>ssm01</finalName>
  </build>



</project>

注意右下角更新pomapache

 

logback.xmlapi

 

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

 

這裏能夠控制輸出格式和內容,有興趣的能夠本身設置spring-mvc

 

jdbc.properties

 

jdbc.driver=com.mysql.jdbc.Driver
#數據庫地址
jdbc.url=jdbc:mysql://xxxxxxxxx:3306/ChatRobot?useUnicode=true&characterEncoding=utf8
#用戶名
jdbc.username=xxxx
#密碼
jdbc.password=xxxxx
#最大鏈接數
c3p0.maxPoolSize=30
#最小鏈接數
c3p0.minPoolSize=10
#關閉鏈接後不自動commit
c3p0.autoCommitOnClose=false
#獲取鏈接超時時間
c3p0.checkoutTimeout=10000
#當獲取鏈接失敗重試次數
c3p0.acquireRetryAttempts=2

 

 

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

    <!-- 掃描service包下全部使用註解的類型 -->
    <context:component-scan base-package="com.test.service"/>

    <!-- 配置數據庫相關參數properties的屬性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 數據庫鏈接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>

    <!-- 配置SqlSessionFactory對象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 掃描model包 使用別名 -->
        <property name="typeAliasesPackage" value="com.test.model"/>
        <!-- 掃描sql配置文件:mapper須要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出須要掃描Dao接口包 -->
        <property name="basePackage" value="com.test.dao"/>
    </bean>

    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入數據庫鏈接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基於註解的聲明式事務 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

 

 

spring-mvc.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.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- 掃描web相關的bean -->
    <context:component-scan base-package="com.test.controller"/>

    <!-- 開啓SpringMVC註解模式 -->
    <mvc:annotation-driven/>

    <!-- 靜態資源默認servlet配置 -->
    <mvc:default-servlet-handler/>

    <!-- 配置jsp 顯示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

 

 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>ssm01</display-name>
    <description>ChatRobot_Alpha_0.0.1</description>

    <!-- 編碼過濾器 -->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置DispatcherServlet -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springMVC須要加載的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 匹配全部請求,此處也能夠配置成 *.do 形式 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

 

User的model

public class User {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }



}

userController

@Controller
@RequestMapping(value = "/test")
public class UserController {
    @Resource
    private IUserService userService;

    @RequestMapping(value = "/save")
    public void saveUser()
    {
        User user=new User();

        user.setUsername("張三");
        user.setPassword("852456");
        userService.insertUser(user);
    }

}

IUserService

public interface IUserService {

    /**
     * 增
     * @param user
     * @return
     */
    public int insertUser(User user);
    /**
     * 刪
     */
    public int deleteUser(int id);
    /**
     * 改
     */
    public int updataUser(User user);
    /**
     * 查
     */
    public User selectUserById(int id);
    /**
     * 查找全部
     */
    public List selectALluser();
}

IUserServiceImpl

@Service("userService")
public class UserServiceImpl implements IUserService {
    @Resource
    private IUserDao userDao;


    public int insertUser(User user) {

        userDao.insertUser(user);
        return 0;
    }

    public int deleteUser(int id) {

        return 0;
    }

    public int updataUser(User user) {
        return 0;
    }


    public User selectUserById(int id) {
        return null;
    }


    public List selectALluser() {
        return null;
    }
}

IUserDao

public interface IUserDao {
    /**
     *添加用戶
     * @param user
     * @return
     */
    int insertUser(User user);

    /**
     * 刪除用戶
     * @param id
     * @return
     */
    int delUser(int id);

    /**
     * 修改用戶
     * @param user
     * @return
     */
    int updateUser(User user);

    /**
     * 根據id查用戶
     * @return
     */
    User selectUserById(int id);

    /**
     * 查找全部用戶
     * @return
     */
    List<User> selectAllUser();
}

UserDao.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.test.dao.IUserDao"><!-- 對應dao層接口的名字 -->
    <!-- 自定義返回結果集 -->
    <resultMap id="userMap" type="UserBean">
        <id property="id" column="id" javaType="java.lang.Integer"></id>
        <result property="username" column="username" javaType="java.lang.String"></result>
        <result property="password" column="password" javaType="java.lang.String"></result>
    </resultMap>
    <!-- 在各類標籤中的id屬性必須和接口中的方法名相同 , id屬性值必須是惟一的,不可以重複使用。parameterType屬性指明查詢時使用的參數類型,
    resultType屬性指明查詢返回的結果集類型-->
    <!-- useGeneratedKeys:( 僅 對 insert 有 用 ) 這 會 告 訴 MyBatis 使 用 JDBC 的getGeneratedKeys
     方法來取出由數據(好比:像 MySQL 和 SQLServer 這樣的數據庫管理系統的自動遞增字段)內部生成的主鍵。默認值: false。
     oracle 不支持應該設置成 useGeneratedKeys="false" 否則會報錯
-->
    <!--keyProperty: (僅對 insert有用)標記一個屬性, MyBatis 會經過 getGeneratedKeys或者經過 insert 語句的 selectKey 子元素設置它的值。默認:不設置。 -->
    <!--#{}中的內容,爲佔位符,當參數爲某個JavaBean時,表示放置該Bean對象的屬性值  -->

    <insert  id="insertUser" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO  t_user (username,password) VALUES (#{username},#{password})
    </insert>

    <delete id="deleteUser" parameterType="int">
        DELETE FROM t_user WHERE id=#{id}
    </delete>

    <update id="updateUser" parameterType="int">
        UPDATE t_user SET username=#{username},password=#{password} WHERE id=#{id}
    </update>

    <select id="selectUserById" >
        SELECT * FROM t_user WHERE id=#{id}
    </select>

    <select id="selectAllUser">
        SELECT * FROM t_user
    </select>

</mapper>

https://www.cnblogs.com/hackyo/p/6646051.html

參考文章https://www.cnblogs.com/kevin1990/p/6231122.html

相關文章
相關標籤/搜索