本文詳細講述如何搭建一個Spring+SpringMVC+Maven+Mybatis+MySQL項目環境。
eclipse、maven 及 mysql的安裝和配置在此不贅述,可參考這裏。
本文demo源碼可參考這裏。
本文demo所用 Eclipse Java EE IDE 版本信息:html
Eclipse Java EE IDE for Web Developers. Version: Neon.3 Release (4.6.3) Build id: 20170314-1500 (c) Copyright Eclipse contributors and others 2000, 2017. All rights reserved. Eclipse and the Eclipse logo are trademarks of the Eclipse Foundation, Inc., https://www.eclipse.org/. The Eclipse logo cannot be altered without Eclipse's permission. Eclipse logos are provided for use under the Eclipse logo and trademark guidelines, https://www.eclipse.org/logotm/. Oracle and Java are trademarks or registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. This product includes software developed by other open source projects including the Apache Software Foundation, https://www.apache.org/.
Maven 配置settings.xml(參考這裏,這是一個很是好的 maven 配置,資源更新速度特別快...):java
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- | This is the configuration file for Maven. It can be specified at two levels: | | 1. User Level. This settings.xml file provides configuration for a single user, | and is normally provided in ${user.home}/.m2/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -s /path/to/user/settings.xml | | 2. Global Level. This settings.xml file provides configuration for all Maven | users on a machine (assuming they're all using the same Maven | installation). It's normally provided in | ${maven.home}/conf/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <!-- localRepository | The path to the local repository maven will use to store artifacts. | | Default: ${user.home}/.m2/repository <localRepository>/path/to/local/repo</localRepository> --> <localRepository>E:\Repositories\Maven</localRepository> <!-- interactiveMode | This will determine whether maven prompts you when it needs input. If set to false, | maven will use a sensible default value, perhaps based on some other setting, for | the parameter in question. | | Default: true <interactiveMode>true</interactiveMode> --> <!-- offline | Determines whether maven should attempt to connect to the network when executing a build. | This will have an effect on artifact downloads, artifact deployment, and others. | | Default: false <offline>false</offline> --> <!-- pluginGroups | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e. | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list. |--> <pluginGroups> <!-- pluginGroup | Specifies a further group identifier to use for plugin lookup. <pluginGroup>com.your.plugins</pluginGroup> --> <pluginGroup>org.mortbay.jetty</pluginGroup> </pluginGroups> <!-- proxies | This is a list of proxies which can be used on this machine to connect to the network. | Unless otherwise specified (by system property or command-line switch), the first proxy | specification in this list marked as active will be used. |--> <proxies> <!-- proxy | Specification for one proxy, to be used in connecting to the network. | <proxy> <id>optional</id> <active>true</active> <protocol>http</protocol> <username>proxyuser</username> <password>proxypass</password> <host>proxy.host.net</host> <port>80</port> <nonProxyHosts>local.net|some.host.com</nonProxyHosts> </proxy> --> </proxies> <!-- servers | This is a list of authentication profiles, keyed by the server-id used within the system. | Authentication profiles can be used whenever maven must make a connection to a remote server. |--> <servers> <!-- server | Specifies the authentication information to use when connecting to a particular server, identified by | a unique name within the system (referred to by the 'id' attribute below). | | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are | used together. | <server> <id>deploymentRepo</id> <username>repouser</username> <password>repopwd</password> </server> --> <!-- Another sample, using keys to authenticate. <server> <id>siteServer</id> <privateKey>/path/to/private/key</privateKey> <passphrase>optional; leave empty if not used.</passphrase> </server> --> <server> <id>releases</id> <username>ali</username> <password>ali</password> </server> <server> <id>Snapshots</id> <username>ali</username> <password>ali</password> </server> </servers> <!-- mirrors | This is a list of mirrors to be used in downloading artifacts from remote repositories. | | It works like this: a POM may declare a repository to use in resolving certain artifacts. | However, this repository may have problems with heavy traffic at times, so people have mirrored | it to several places. | | That repository definition will have a unique id, so we can create a mirror reference for that | repository, to be used as an alternate download site. The mirror site will be the preferred | server for that repository. |--> <mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | <mirror> <id>mirrorId</id> <mirrorOf>repositoryId</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://my.repository.com/repo/path</url> </mirror> --> <mirror> <!--This sends everything else to /public --> <id>nexus</id> <mirrorOf>*</mirrorOf> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </mirror> <mirror> <!--This is used to direct the public snapshots repo in the profile below over to a different nexus group --> <id>nexus-public-snapshots</id> <mirrorOf>public-snapshots</mirrorOf> <url>http://maven.aliyun.com/nexus/content/repositories/snapshots/</url> </mirror> </mirrors> <!-- profiles | This is a list of profiles which can be activated in a variety of ways, and which can modify | the build process. Profiles provided in the settings.xml are intended to provide local machine- | specific paths and repository locations which allow the build to work in the local environment. | | For example, if you have an integration testing plugin - like cactus - that needs to know where | your Tomcat instance is installed, you can provide a variable here such that the variable is | dereferenced during the build process to configure the cactus plugin. | | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles | section of this document (settings.xml) - will be discussed later. Another way essentially | relies on the detection of a system property, either matching a particular value for the property, | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'. | Finally, the list of active profiles can be specified directly from the command line. | | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact | repositories, plugin repositories, and free-form properties to be used as configuration | variables for plugins in the POM. | |--> <profiles> <profile> <id>development</id> <repositories> <repository> <id>central</id> <url>http://central</url> <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases> <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>central</id> <url>http://central</url> <releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases> <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots> </pluginRepository> </pluginRepositories> </profile> <profile> <!--this profile will allow snapshots to be searched when activated--> <id>public-snapshots</id> <repositories> <repository> <id>public-snapshots</id> <url>http://public-snapshots</url> <releases><enabled>false</enabled></releases> <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>public-snapshots</id> <url>http://public-snapshots</url> <releases><enabled>false</enabled></releases> <snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> <activeProfiles> <activeProfile>development</activeProfile> <activeProfile>public-snapshots</activeProfile> </activeProfiles> </settings>
開始搭建項目:mysql
1.mysql 數據庫及表準備:git
CREATE TABLE `T_USER` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_type` tinyint(4) DEFAULT NULL COMMENT '0、系統管理,一、業務管理員,二、普通操做員', `mobile` varchar(255) DEFAULT NULL COMMENT '管理員手機號', `is_biz_operator` tinyint(4) DEFAULT NULL COMMENT '是否業務操做員 0: 不是 1:是的', `is_sys_operator` tinyint(4) DEFAULT NULL COMMENT '是否系統操做員 0: 不是 1:是的', `login_name` varchar(255) NOT NULL COMMENT '員工後臺管理帳號', `real_name` varchar(100) DEFAULT NULL COMMENT '用戶名', `password` varchar(255) NOT NULL COMMENT '員工後臺管理密碼', `status` tinyint(4) NOT NULL COMMENT '是否有效 0:無效 1:有效', `creator` bigint(20) DEFAULT NULL COMMENT '建立者', `updator` bigint(20) DEFAULT NULL COMMENT '更新者', `create_date` datetime DEFAULT NULL COMMENT '建立日期', `update_date` datetime DEFAULT NULL COMMENT '更新日期', `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0:沒刪除 1:刪除', PRIMARY KEY (`id`), UNIQUE KEY `unique_login_name` (`login_name`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8;
2.maven 工程建立
工程新建完成後,工程的目錄結構以下:github
3.編輯 pom.xml 文件,添加工程的包依賴web
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hy</groupId> <artifactId>ssm001</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <!-- spring版本號 --> <spring.version>3.2.8.RELEASE</spring.version> <!-- log4j日誌文件管理包版本 --> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <!-- junit版本號 --> <junit.version>4.10</junit.version> <!-- mybatis版本號 --> <mybatis.version>3.2.1</mybatis.version> </properties> <dependencies> <!-- 添加Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</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-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--單元測試依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- 日誌文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!--spring單元測試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </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.2.0</version> </dependency> <!-- mysql驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> </dependencies> </project>
4.配置文件初始化。
分別初始化mybatis配置文件、數據庫配置文件、Spring配置文件。spring
mybatis配置文件 mybatis-config.xml:sql
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
數據庫配置文件 jdbc.properties:數據庫
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://192.168.8.*:3306/db_user jdbc_username=* jdbc_password=*
spring配置文件 application.xml:express
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入jdbc配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/*.properties</value> <!--要是有多個配置文件,只需在這裏繼續添加便可 --> </list> </property> </bean> <!-- 配置數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!-- 不使用properties來配置 --> <!-- <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/learning" /> <property name="username" value="root" /> <property name="password" value="christmas258@" /> --> <!-- 使用properties來配置 --> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> </bean> <!-- 自動掃描了全部的XxxxMapper.xml對應的mapper接口文件,這樣就不用一個一個手動配置Mpper的映射了,只要Mapper接口類和Mapper映射文件對應起來就能夠了。 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.hy.dao" /> </bean> <!-- 配置Mybatis的文件 ,mapperLocations配置**Mapper.xml文件位置,configLocation配置mybatis-config文件位置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml"/> <!-- <property name="mapperLocations" value="com.hy.mapper"/> --> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model" /> --> </bean> <!-- 自動掃描註解的bean --> <context:component-scan base-package="com.hy.service" /> </beans>
5.mybatis 反向生成代碼
MyBatis屬於一種半自動的ORM框架,因爲手寫Mapping映射文件很容易出錯,因此可利用 MyBatis生成器 自動生成實體類、DAO接口和Mapping映射文件。有兩種方式:
第一種方式:安裝 eclipse mybatis generator 插件,使用該插件實現代碼生成。
可參考這裏。
第二種方式:直接用 mybatis-generator.jar 包的命令方式。
相關的jar包及命令可查看本demo源碼:
在本文的 demo 中使用了第二種方式。mybatis generator 配置文件generatorConfig.xm內容以下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 數據庫驅動--> <classPathEntry location="mysql-connector-java-5.1.29.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--數據庫連接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.8.*:3306/db_user" userId="*" password="***"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.hy.domain" targetProject="../../java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="mapper" targetProject="../../resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.hy.dao" targetProject="../../java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--> <table tableName="T_USER" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
cd:G:\javaSpace\ssm001\src\main\resources\mybatis-generator java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
執行以上命令後,工程目錄中生成了與 mybatis 相關的代碼,主要有實體類、DAO接口和Mapping映射文件。
6.接口聲明並實現接口
聲明一個UserService接口:
package com.hy.service; import com.hy.domain.User; public interface UserService { User getUserById(Long id); }
新建一個類 UserServiceImpl,並實現 UserService 接口 :
package com.hy.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hy.dao.UserMapper; import com.hy.domain.User; import com.hy.service.UserService; @Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.selectByPrimaryKey(id); } }
7.單元測試
單元測試是爲了驗證第6步中 UserService 接口的 getUserById 方法。
com.hy.baseTest 中新增類 SpringTestCase.java,使用 SpringJUnit4ClassRunner 實現單元測試:
package com.hy.baseTest; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //指定bean注入的配置文件 @ContextConfiguration(locations = { "classpath:application.xml" }) //使用標準的JUnit @RunWith註釋來告訴JUnit使用Spring TestRunner @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestCase extends AbstractJUnit4SpringContextTests { }
在 com.hy.test 中新增 UserServiceTest 類文件:
package com.hy.test; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.hy.baseTest.SpringTestCase; import com.hy.domain.User; import com.hy.service.UserService; public class UserServiceTest extends SpringTestCase { @Autowired private UserService userService; @Test public void selectUserByIdTest(){ User user = userService.getUserById((long) 1); System.out.println("userLoginName:" + user.getLoginName()); } }
運行單元測試:UserServiceTest 右鍵 Run As –>Junit Test, 運行結果:
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner). log4j:WARN Please initialize the log4j system properly. userLoginName:admin
到此,咱們已經搭建了一個基於 Spring+Maven+Mybatis+Mysql 的項目環境。文中使用了不少Spring相關的技術,如自動注入註解@Service、@Autowired,以及Spring配置文件,這些知識可參考:
http://www.cnblogs.com/szlbm/...