设为首页 收藏本站
查看: 1319|回复: 0

[经验分享] 【自虐1.2】Srping+MyBatis完成CRUD

[复制链接]

尚未签到

发表于 2016-11-27 11:10:26 | 显示全部楼层 |阅读模式
环境:win7 MyEclipse10 jdk1.6 tomcat7 SpringMVC2.5 MySQL
 
从前文

http://340413629-qq-com.iyunv.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包中找
 

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-306135-1-1.html 上篇帖子: mybatis+proxool 实现第三方数据库连接池 下篇帖子: spring整合mybatis,关于注入Dao对象出错问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表