Maven+Eclipse+SpringMVC+MyBatis整合
参考:Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(一):
[url]http://www.blogjava.net/bolo/archive/2011/05/23/349655.html[/url]
Maven最佳实践:版本管理:[url]http://juvenshun.iteye.com/blog/376422[/url]
[color=red][b]使用Eclipse构建Maven的SpringMVC项目[/b][/color]:[url]http://limingnihao.iteye.com/blog/830409[/url]
[b][color=red]基于namespace接口与公用dao的区别[/color][/b],从MyBatis3.0开始,对mapper中的namespace属性新增了一个特性:可以指定具体的接口来作为持久化操作类,在接口中定义与映射文件中id属性值相同的方法,MyBatis会自动去绑定和执行对应的SQL语句。这种接口实现方式,需要为每个Mapper创建一个接口,如果系统做大了,维护这些类会比较麻烦,大象个人倾向于基础服务式的Dao实现类.
首先是pox.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.pas</groupId>
<artifactId>ssm3</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ssm3 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>3.2.1.RELEASE</spring.version>
<mybatis.version>3.1.1</mybatis.version>
<mybatis.spring.version>1.1.1</mybatis.spring.version>
<aspectj.version>1.6.10</aspectj.version>
<jetty.version>6.1.26</jetty.version>
<tomcat.version>2.1-SNAPSHOT</tomcat.version>
<junit.version>3.8.1</junit.version>
<mysql.version>5.1.23</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</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-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-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- <dependency> <groupId>org.aspectj</groupId> <artifactId>acpectjrt</artifactId>
<version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId>
<artifactId>acpectjweaver</artifactId> <version>${aspectj.version}</version>
</dependency> -->
</dependencies>
<build>
<finalName>ssm3</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>${jetty.version}</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat.version}</version>
</plugin>
<plugin>
<!-- 注解支持,jdk5才具有的新特性,我们需要设置compile插件,具体可以参考Setting the -source and
-target of the Java Compiler,根据说明,我们继续向pom文件中加入 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>5</source>
<target>5</target>
</configuration>
</plugin>
<plugin>
<!-- 我们想将所有的依赖库都打包,直接交给用户,这样用户不需要在做其他设置了,这里需要使用Assembly插件了,其说明参考Pre-defined
Descriptor Files,这个参考文件也说明了有四种默认定义的打包方式,我们选择jar-with-dependencies,继续添加pom文件 -->
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>$/lib</outputDirectory>
<!-- 拷贝所以依赖存放位置 -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<display-name></display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>ssm3</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ssm3</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/pasystem
username=root
password=
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<context:component-scan base-package="com">
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 事务处理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- sqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Mapper的配置,莫非每个Mapper都要配置?不能注解?那也是个负担... -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.pas.mapper.IUserMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
ssm3-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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
mybatis-config.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>
<!-- 设定别名,这里可以设定一些常用的别名,在Mapper可以使用,但是由于数据库的字段会存在下划线等,而java里面又不推荐使用,所以类似这样,就不推荐使用,而是使用resultMap和paramterMap -->
<typeAliases>
<typeAlias alias="defaultUser" type="com.pas.dao.domain.User"></typeAlias>
</typeAliases>
<!-- 增加mapper.xml文件 -->
<mappers>
<mapper resource="com/pas/dao/xml/User.xml" />
</mappers>
</configuration>
src/main/java/com/pas/dao/xml/User.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">
<!-- 接口方式的时候, namespace要定义成Mapper的接口名字 -->
<mapper namespace="com.pas.mapper.IUserMapper">
<resultMap type="com.pas.dao.domain.User" id="RUser">
<id property="userId" column="user_id"/>
<result property="code" column="code"/>
<result property="password" column="password"/>
<result property="email" column="email"/>
<result property="state" column="state"/>
</resultMap>
<parameterMap type="com.pas.dao.domain.User" id="PUser">
<parameter property="userId" javaType="int" />
<parameter property="code" />
<parameter property="password" />
<parameter property="email" />
<parameter property="state" />
</parameterMap>
<select id="queryUserById" parameterType="int" resultMap="RUser">
select user_id, code,password,email, state from User where user_id = #{userId}
</select>
<select id="queryUserByName" parameterType="string" resultMap="RUser">
select user_id, code,password,email, state from User where code = #{code}
</select>
<insert id="insertUser" parameterMap="PUser">
insert into User(user_id, code,password,email, state) values(#{userId}, #{code},#{password},#{email}, #{state})
</insert>
<update id="updateUser">
update User set code=#{code},password=#{password},email=#{email},state=#{state} where user_id=#{userId}
</update>
</mapper>
User.java
package com.pas.dao.domain;
import java.util.Date;
public class User {
private int userId;
private String code;
private String password;
private String email;
private String state;
private String createBy;
private Date createDatetime;
private String modifyBy;
private Date modifyDatetime;
......
}
两种方式
[color=red][b]DAO方式:[/b][/color]
接口
IUsersDao.java
package com.pas.dao;
import java.util.List;
public interface IUsersDao {
@SuppressWarnings("rawtypes")
public abstract List queryUserByName(String name);
}
实现类
UsersDao.java
package com.pas.dao.impl;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import com.pas.dao.IUsersDao;
/**
* 这个是使用dao方式,这种方式可以处理自定义异常等.
* @author Administrator
*
*/
@Repository
public class UsersDao extends SqlSessionDaoSupport implements IUsersDao {
@SuppressWarnings("rawtypes")
@Override
public List queryUserByName(String name) {
System.out.println("Users.queryUserByName()");
//com.pas.mapper.IUserMapper.queryUserByName 这里是空间名字+sql id
return getSqlSession().selectList("com.pas.mapper.IUserMapper.queryUserByName", name);
}
}
[color=red][b]接口+namespace方式:[/b][/color]
Mapper接口
IUserMapper.java
package com.pas.mapper;
import com.pas.dao.domain.User;
/**
* 这里是Mapper接口,接口定义的方法一定跟User.xml里面的sql id一致,否则会出现错误.
* @author Administrator
*
*/
public interface IUserMapper {
public abstract User queryUserById(int id);
public abstract void insertUser(User user);
public abstract void updateUser(User user);
}
UserMapper.java
package com.pas.mapper.impl;
import com.pas.dao.domain.User;
import com.pas.mapper.IUserMapper;
/**
* 这个是Mapper接口方式,接口的方法名字就直接对应User.xml里面的SQL ID.<p>
* 在实现类里面实现并直接使用接口,其实这个接口的实现就是User.xml
* @author Administrator
*
*/
public class UserMapper implements IUserMapper {
private IUserMapper userMapper;
@Override
public User queryUserById(int id) {
return userMapper.queryUserById(id);
}
@Override
public void insertUser(User user) {
System.out.println("userMapper insertUser");
userMapper.insertUser(user);
}
@Override
public void updateUser(User user) {
System.out.println("userMapper updateUser");
userMapper.updateUser(user);
}
public IUserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(IUserMapper userMapper) {
this.userMapper = userMapper;
}
}
Service:
接口:这个接口并不是必要的
IUsersService.java
package com.pas.service;
import com.pas.dao.domain.User;
public interface IUsersService {
public abstract User queryUsersById(int id);
public abstract User queryUsersByName(String name);
public abstract void saveUser(User user);
}
实现类:
UsersServiceImpl.java
package com.pas.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.pas.dao.IUsersDao;
import com.pas.dao.domain.User;
import com.pas.mapper.IUserMapper;
import com.pas.service.IUsersService;
@Service(value="usersService")
@Transactional(rollbackFor=Exception.class)
public class UsersServiceImpl implements IUsersService {
@Resource(name="userMapper")
private IUserMapper userMapper;
@Resource(name="usersDao")
private IUsersDao usersDao;
@Override
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
public User queryUsersById(int id){
return userMapper.queryUserById(id);
}
/**
* 使用dao方式
*/
@SuppressWarnings("rawtypes")
@Override
@Transactional(propagation=Propagation.REQUIRED, readOnly=true)
public User queryUsersByName(String name){
List list = usersDao.queryUserByName(name);
System.out.println("list = "+list==null?"0":list.size());
if(list!=null&&list.size()>0) return (User)list.get(0);
return null;
}
/**
* 使用Mapper接口方式
*/
@Override
@Transactional(propagation=Propagation.REQUIRED)
public void saveUser(User user){
if(user.getUserId()<=0){
System.out.println("insertUser");
userMapper.insertUser(user);
}else{
System.out.println("updateUser");
userMapper.updateUser(user);
}
//throw new RuntimeException("@@ Rollback for Debug..........");
}
}
Controller类:
TestController.java
package com.pas.controller;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pas.dao.domain.User;
import com.pas.service.IUsersService;
@Controller
public class TestController {
@Resource(name = "usersService")
private IUsersService usersService;
@RequestMapping(value = "/doTest.do")
public String doTest() {
User user = new User();
user.setCode("pandy");
user.setEmail("afasdf");
user.setPassword("pandy");
user.setState("001");
user.setCreateBy("01");
user.setCreateDatetime(new Date());
user.setModifyBy("001");
user.setModifyDatetime(new Date());
usersService.saveUser(user);
user = usersService.queryUsersById(1);
user = usersService.queryUsersByName("pandy");
System.out.println("Test success.......");
return "success";
}
}
标签:SpringMVC,Eclipse,Maven,User,org,import,com,public,user
From: https://blog.51cto.com/u_3871599/6338602