基于maven进行spring 和mybatis的整合(Myeclpise)

学习日记:基于maven进行spring和mybatis的整合,进行分页查询

  什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译、构建、测试、发布和报告等。在大型项目开发中,使用maven来管理是必不可少的。

  开发工具myeclipse:myclipse 10.0自带了maven的插件。也可以网上下载maven插件

  1、新建一个maven project,点击next,选择maven-archetype-webapp,点击next,填写Group ID和ArtiFact Id;

   Group ID:指明创建项目的组织或者小组的唯一标识。GroupId是项目的关键标识,典型的,此标识以组织的完全限定名来定义。比如,org.apache.maven.plugins是所有Maven插件项目指定的groupId;

   ArtiFact Id:指明此项目产生的主要产品的基本名称。项目的主要产品通常为一个JAR文件。第二,象源代码包通常使用artifactId作为最后名称的一部分。典型的产品名称使用这个格式: <artifactId><version>;

   version:版本号,格式通常为x.x.x-里程碑。通常情况下,第一个x表示程序架构上发生重大变化,第二个x表示程序架构中的分支变化,第三个x表示程序改动的次数。常见的里程碑有如下值:① SNAPSHOT,快照版,

   正在开发的版 本;② Alpha,是内部测试版,一般不向外部发布,会有很多Bug,一般只有测试人员使用;③ Beta,公共测试版,通常有客户单位参与的测试;④ Release,即Release Candidate,候选版本,

   RC版不会再加入新的功能了,主要着重于除错;⑤ GA,即General Availability,正式发布的版本。

    基于maven进行spring 和mybatis的整合(Myeclpise)

   

  1.1目录结构: 

    基于maven进行spring 和mybatis的整合(Myeclpise) 

    src/main/java:该文件夹所有的java代码

    src/main/resources:该文件编写所有的配置文件

    src/test/java:编写所有的测试代码

    src/test/resources:编写所有的测试的配置文件

    webapp:相当于普通web工程的webroot目录

  2、配置pom.xml文件,pom.xml是maven开发的核心,因为所有的jar包都是通过maven配置的方式导入。

    spring和mybatisd的配置都能够在官网或者github上找到:

    spring配置:http://projects.spring.io/spring-framework/

    mybatis配置:http://mybatis.github.io/mybatis-3/zh/getting-started.html

    由于配置太多,大家可以参考一下我的配置:

    

        <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>edu.dave_market</groupId>
<artifactId>dave_market</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>dave_market Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<!-- spring版本号 -->
<spring.version>3.2.9.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- log4j日志管理 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.16</log4j.version>
</properties> <!-- 依赖 -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 添加servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- json依赖start -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency> <!-- 添加spring start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-web</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</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-webmvc</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-context-support</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.9.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring配置end -->
<!-- 配置mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- 配置spring和spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 配置连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.13</version>
</dependency> <!-- 配置日志 start-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- 配置日志 end-->
<!-- 分页主键 start-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!-- 分页主键end -->
</dependencies> <build>
<finalName>dave_market</finalName>
<!-- 添加插件 -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<!-- 添加参数 -->
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
include>**/*.*</include>
</includes>
</resource>
</resources> </build>
</project>

    3、配置mybatis的配置文件,因为是基于spring进行开发所以正在spring中扫描mapper接口的时候,也对mapper.xml文件进行扫描(注意:mapper接口必须和mapper.xml位于同一目录下面)

    

<?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>
 <!--为model添加别名-->
<typeAliases>
<!-- 批量配置 -->
<package name="edu.market.model"/>
</typeAliases>
</configuration>

     

    4、配置applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--加载数据库连接文件-->
<context:property-placeholder location="classpath:db.properties"/>
 <!--扫描bean,将bean对象注入容器中-->
<context:component-scan base-package="edu.market.service"/>
<context:component-scan base-package="edu.market.controller"/>
<!--开启注解开发-->
<mvc:annotation-driven/>
<!--配置视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置数据源,这里使用的是阿里巴巴的数据源,jar包在pom.xml文件中已经配置ok-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="5" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> <!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
<!--数据源配置结束-->
  
  <!--配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations">
<list>
<value>edu/market/mapper/*Mapper.xml</value>
</list>
</property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
</value>
</property>
</bean>
</array>
</property>
</bean> <!--批量扫描mapper文件,将mapper接口注入spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="edu.market.mapper"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/> <!-- 对数据源进行事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
</beans>

    5、配置web.xml文件

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 加载spring容器(mapper、service、controller已经加载到spring) -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring/applicationContext-*.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- post乱码问题解决 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置前端控制器 -->
<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:config/spring/applicationContext.xml</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> <display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

    

    6、编写mapper和mapper.xml(注意,mapper的接口中的方法名要和mapper.xml文件中的id名相对应)

  

<?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="edu.market.mapper.UserMapper"> <sql id="usercol">
(uid,username,password,email,state,lastlogin)
</sql> <select id="findUserById" parameterType="int" resultType="user">
select * from user where id=#{id}
</select> <select id="findAllUser" resultType="user">
select * from user
</select> <select id="findUserByName" parameterType="java.lang.String" resultType="user">
select * from user where username=#{value}
</select>
</mapper>
package edu.market.mapper;

import java.util.List;

import edu.market.model.User;

public interface UserMapper {
//根据id查询用户
public User findUserById(Integer id);
//查询所有用户
public List<User> findAllUser();
//根据用户名查询用户
public User findUserByName(String username);

  7、service实现类,service接口的代码我就不贴了

package edu.market.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import edu.market.mapper.UserMapper;
import edu.market.model.User;
import edu.market.service.UserService; @Service("userService")
public class UserServiceImpl implements UserService{ @Autowired
private UserMapper userMapper; public User findUserById(Integer id) {
return userMapper.findUserById(id);
} @Override
public List<User> findAllUser() {
List<User>userList=userMapper.findAllUser();
return userList;
} @Override
public User findUserByName(String username) {
return userMapper.findUserByName(username);
} }

  8、controller层的实现

package edu.market.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.github.pagehelper.PageHelper; import edu.market.model.User;
import edu.market.service.UserService; @Controller
public class UserController {
@Autowired
private UserService userService; @RequestMapping("findUserById")
public String findUserById(Model model) {
User user = userService.findUserById(10);
model.addAttribute("user", user);
return "index";
} @RequestMapping("findAllUser")
public String findAllUser(Model model) {
    在这里掉用了PageHelper.startPage(1, 4),第一个参数是第几页,第二个参数是每页条数
PageHelper.startPage(1, 4);
List<User> userList = userService.findAllUser();
model.addAttribute("userList", userList);
System.out.println(Arrays.toString(userList.toArray()));
return "index";
} @RequestMapping("findUserByName")
public void findUserByName(String username, HttpServletResponse response) {
User user = userService.findUserByName(username);
try {
PrintWriter out = response.getWriter();
if (user != null) {
out.print(true);
} else {
out.print(false);
}
} catch (IOException e) {
e.printStackTrace();
}
} @RequestMapping("checkPassword")
public void checkPassword(String username, String password,
HttpServletResponse response) {
User user = userService.findUserByName(username);
try {
PrintWriter out = response.getWriter();
if (user != null && password.equals(user.getPassword())) {
if(user.getState()!=1){
out.print("2");
}else{
out.print("1");
}
} else {
out.print("0");
} } catch (IOException e) {
e.printStackTrace();
}
} @RequestMapping("login")
public String login(User user,HttpSession session){
System.out.println(1);
session.setAttribute("user", user);
return "redirect:index.html";
} }
上一篇:Simple Validation in WPF


下一篇:Linux命令详解之—more命令