`
零度弥合
  • 浏览: 20607 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

【自虐1.2】Srping+MyBatis完成CRUD

 
阅读更多

环境:win7 MyEclipse10 jdk1.6 tomcat7 SpringMVC2.5 MySQL

 

从前文

http://340413629-qq-com.iteye.com/blog/2034778

修改而来,目的是加入Mybatis

 

首先总结一点web.xml的知识

<context-param></context-param> 用来设定web站台的环境参数,它包含两个子元素:
    <param-name></param-name> 用来指定参数的名称
    <param-value></param-value> 用来设定参数值

比如:
<context-param>
    <param-name>my_param</param-name>
    <param-value>hello</param-value>
</context-param>

在此设定的参数,可以在servlet中用 getServletContext().getInitParameter("my_param") 来取得

那如下这样写是怎么回事呢

  <context-param>  

        <param-name>contextConfigLocation</param-name>  

        <param-value>/WEB-INF/*context.xml</param-value>  

    </context-param>  

原来contextConfigLocation 参数定义了要装入的 Spring 配置文件。

据说是这样一个监听器去加载的

  <listener>   
       <listener-class> org.springframework.web.context.ContextLoaderListener listener-class >   
  </listener>

默认会加载/WEB-INF/下的applicationContext.xml。

但如果配置好contextConfigLocation之后就不加载默认的了

反过来讲此listener也正是为了在服务器启动时加载spring配置文件而存在

以上都是看网上别人的博文,并测试后得知,我并不知道其中原理,所以并不确定。

 

那来看一下我的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">
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/*context.xml</param-value>
	</context-param>
	<servlet>
		<servlet-name>hello</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>WEB-INF/spring-servlet.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>hello</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>
</web-app>

 

 如上所述context-param就是服务器启动时会被读进内存的,而注册org.springframework.web.context.ContextLoaderListener之后再配置进contextConfigLocation中的就是spring的配置文件

也就是说交给spring管理

我这里只配置了一个我取名spring-db-context.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"
	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">

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
	</bean>
	
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
	</bean>
	
</beans>
 

 

第一个bean是把properties文件读进内存,在本文中可以用${name}来引用

dataSrouce和使用JDBC时是一样的

来看sqlSessionFactory和sqlSession

我记得这样一段代码,在不使用spring时,mybatis是这样生成的

DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);

 

可见,这里是把生成sqlsessionFactory的工作交给了spring来依赖注入

当然,这里必须有mybatis的spring插件包才能跑通

 

在SqlMapConfig.xml中我几乎什么都没配置,精简期间嘛

<?xml version="1.0" encoding="GB2312" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<mappers>
		<mapper resource="cn/zinue100/vo/UserMapper.xml" />
	</mappers>
</configuration>

 

那来看看Mapper

 

<?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="cn.zinue100.vo.UserMapper">
	<insert id="insert" parameterType="cn.zinue100.vo.User"
		useGeneratedKeys="true" keyProperty="id">
    	INSERT INTO user(username,password,email) VALUES(
    		#{username,jdbcType=VARCHAR},
        	#{password,jdbcType=VARCHAR},
        	#{email,jdbcType=VARCHAR})
	</insert>
	<update id="update" parameterType="cn.zinue100.vo.User">
        UPDATE user SET
	        username = #{username,jdbcType=VARCHAR},
	        password = #{password,jdbcType=VARCHAR},
	        email = #{email,jdbcType=VARCHAR}
        <where>
        <if test='username!=null'>and username=#{username,jdbcType=VARCHAR}</if>
   		<if test='id!=0'>and id=#{id,jdbcType=INTEGER}</if>
   		</where> 
	</update>

	<delete id="delete" parameterType="cn.zinue100.vo.User">
		delete from user 
        <where>
        <if test="username!=null">and username=#{username,jdbcType=VARCHAR}</if>
   		<if test="id!=0">and id=#{id,jdbcType=INTEGER}</if> 
   		</where>
	</delete>

	<select id="selectById" resultType="cn.zinue100.vo.User"
		parameterType="Integer">
		select id,username,password,email 
		from user 
		where id = #{id}
	</select>

	<select id="selectByName" resultType="cn.zinue100.vo.User"
		parameterType="String">
		select id,username,password,email 
		from user
		where username=#{username}
	</select>

	<select id="selectAll" resultType="cn.zinue100.vo.User">
		select id,username,password,email from user
	</select>
</mapper>

 

 我发现动态SQL已经和我三四年前用的不同了,只需要<where> <if>简洁多了

最后来看看UserDaoImpl.java吧

package cn.zinue100.dao.myBaitsImpl;

import java.util.Map;
import javax.annotation.Resource;
import org.mybatis.spring.SqlSessionTemplate;
import cn.zinue100.dao.UserDao;
import cn.zinue100.vo.User;

public class UserDaoImpl implements UserDao {

	private static final String INSERT = "insert";
	private static final String UPDATE = "update";
	private static final String DELETE = "delete";
	private static final String SELECTALL = "selectAll";
	private static final String SELECTBYID = "selectById";
	private static final String SELECTBYNAME = "selectByName";

	private SqlSessionTemplate sqlSession;

	public void addUser(User user) {
		String sql = this.getStatementId(User.class, INSERT);
		this.sqlSession.insert(sql, user);
	}

	public void deleteUser(User user) {
		String sql = this.getStatementId(User.class, DELETE);
		this.sqlSession.delete(sql, user);
	}

	public void updateUser(User user) {
		String sql = this.getStatementId(User.class, UPDATE);
		sqlSession.update(sql, user);
	}

	public Map<String, User> getUsers() {
		String sql = this.getStatementId(User.class, SELECTALL);
		return this.sqlSession.selectMap(sql,"username");
	}

	public User getUserById(int id) {
		String sql = this.getStatementId(User.class, SELECTBYID);
		return sqlSession.selectOne(sql, id);
	}

	public User getUserByName(String name) {
		String sql = this.getStatementId(User.class, SELECTBYNAME);
		User user = sqlSession.selectOne(sql,name);
		return user;
	}

	private String getStatementId(Class entityClass, String suffix) {
		String sqlStr = entityClass.getName() + "Mapper." + suffix;
		System.out.println("getStatementId:" + sqlStr);  
		return sqlStr;
	}

	public SqlSessionTemplate getSqlSession() {
		return sqlSession;
	}

	@Resource
	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}

}

 

最后执行的sql语句用这样一个方法来生成

private String getStatementId(Class entityClass, String suffix) {
	String sqlStr = entityClass.getName() + "Mapper." + suffix;
	System.out.println("getStatementId:" + sqlStr);  
	return sqlStr;
}

 

 使用的字符串是刚才Mapper文件的namespace加上id。

因为我的类名和命名空间名一样,只是加了个Mapper,所以用类名(带路径)就可以找到

 

其他的代码不贴了放在附件中

 

附件中的lib包只放了需要增加的jar包,如果想凑齐全部jar包,那可以去这个系列前面的所有lib包中找

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics