首页 > 其他分享 >Maven+Eclipse+SpringMVC+MyBatis整合

Maven+Eclipse+SpringMVC+MyBatis整合

时间:2023-05-24 13:06:00浏览次数:42  
标签:SpringMVC Eclipse Maven User org import com public user


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

相关文章

  • 使用Maven管理Web工程
    使用命令创建webapp工程:到workdpace运行命令[b][color=red]mvnarchetype:create-DgroupId=com.pandy-DartifactId=MavenDemo-DarchetypeArtifactId=maven-archetype-webapp[/color][/b]使用maven构建web项目实例[url]http://hnzhoujunmei.iteye.com/......
  • 学习Maven的使用
    学习maven的使用:[url]http://fluagen.blog.51cto.com/146595/40086[/url]Maven试用手记----开始一个新的项目并编译和测试:[url]http://www.blogjava.net/lvdougao/articles/26827.html[/url]maven编译命令:[url]http://radio123.iteye.com/blog/1490......
  • Appengine部署springMVC3.1
    参考:[url]http://sikeh.iteye.com/blog/364043[/url]获得springMVC的方法:[url]http://panyongzheng.iteye.com/blog/1759912[/url][b]1.mvnarchetype:create-DgroupId=com.pandy-DartifactId=study[/b][b]2.cdstudy[/b]需要做一些另外的事情,然......
  • Maven的概述
    Maven的概述@目录Maven的概述2.依赖3.Maven的工作机制3.最后:感谢Java项目开发过程中,构建指的是使用『原材料生产产品』的过程。原材料Java源代码基于HTML的Thymeleaf文件图片配置文件……产品一个可以在服务器上运行的项目构建过程包含的主要的环节:......
  • 浅聊springmvc的执行流程
    核心组件是DispatcherServlet,所有的流程都是通过这个组件进行转发的,就好像一个转运中心1、用户发送请求至前端控制器DispatcherServlet。2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。3、处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生......
  • Maven安装与配置
    Maven安装与配置1.下载Mavenhttps://maven.apache.org/download.cgi这里面的第二个:2.配置Maven环境变量此电脑->右键属性->下面点击高级系统设置->点击环境变量设置->用户变量中新建:变量名:M2_HOME 变量值:Maven所在目录(比如:E:\apache-maven-3.9.2-bin\apache-maven-......
  • Maven报错 解决方案。ERROR: No goals have been specified for this build. You must
    转:https://www.codeleading.com/article/61821466327/报错:[ERROR]Nogoalshavebeenspecifiedforthisbuild.Youmustspecifyavalidlifecyclephaseoragoalintheformat<plugin-prefix>:<goal>or<plugin-group-id>:<plugin-artifact-......
  • SpringMVC响应json数据
    SpringMvc响应json数据@Controller@RequestMapping("/json")publicclassJsonController{@RequestMapping("/js1")@ResponseBody//响应json:将return的值作为文本响应给客户端,而不是转发到对应页面publicStringjs1(){System.out.println("js......
  • springmvc的流程及简单案例
    springmvc概念JavaEE体系结构包括四层,从上到下分别是应用层、Web层、业务层、持久层。Struts和SpringMVC是Web层的框架,Spring是业务层的框架,Hibernate和MyBatis是持久层的框架。SpringMVC是一种轻量级的、基于MVC的Web层应用框架,它属于Spring框架的一部分。SpringMVC说......
  • 记一次IDEA运行maven命令异常退出,Process finished with exit code -1073741819 (0xC
    系统是基于ARM64的win11,问题根源也不是网传的金山毒霸,出问题的也不是我。起因,我一学弟想在他的微软surfacepro上装IDEA学java,然后给他整了个i586版本的jdk(也就是32位jdk).后面他学习的时候用到tomcat,然后一运行项目啊,发现tomcat是64位,32位的jdk运行不起来,然后把jdk换成了64......