springMvc+ibatis+mybatis入门开发

来源:互联网 发布:比特币 2013年淘宝 编辑:程序博客网 时间:2024/05/31 05:28

 首先添加开发的所需架包,spring+ibatis+mybatis架包如下:



下面创建User类以及映射文件

User.java

<span style="font-size:14px;"><span style="font-size:14px;">package com.entity;public class User {private int id;private String name;private String pwd;public User(){}public User(String name,String pwd){this.name=name;this.pwd=pwd;}public User(int id,String name,String pwd){this.id=id;this.name=name;this.pwd=pwd;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}}</span></span>
User_ibatis.xml

<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMap  PUBLIC "-//ibatis.apache.org//DTD SQL MAP 2.0//EN"  "http://ibatis.apache.org/dtd/sql-map-2.dtd">  <sqlMap><!-- 可以加个namespace命名空间,在外面调用就可以"xx.getAll"方法了 --><!-- <typeAlias>元素 <typeAlias>元素为一个通常较长的、全限定类名指定一个较短的别名。 <typeAlias alias="shortname" type="com.long.class.path.Class"/>  --><typeAlias alias="User" type="com.entity.User"/><!--id对应外面调用的方法名resultClass 返回结果类型(对象/类名、int、String...)  parameterClass 参数类型(对象/类名、int、String...)--><!-- 条件查询 --><select id="login" resultClass="User">select * from Users where name=#name# </select><!-- 登陆查询 ,多条件查询/传参(类名/类型) 返回user对象--><!-- 妈的,又行不通了 --><select id="login2" resultClass="User" parameterClass="User">select * from Users where name=#name# and pwd=#pwd#</select><!-- 查询总数据,返回int类型 --><select id="getCount" resultClass="int">select count(id) from Users</select><!-- 根据id查询uname,返回String类型 ,参数id--><select id="getName" resultClass="String">select name from Users where id=#id#</select><!-- 查询所有 --><select id="getAll" resultClass="User">select name from Users</select><!-- 模糊查询 --><!-- parameterClass="String" 可有可无--><select id="getLike" resultClass="User" parameterClass="String">select * from Users where name like '%$name$%'</select><!-- 添加操作1 --><insert id="addUser" parameterClass="User">insert into User(name,pwd) values(#name#,#pwd#)<selectKey resultClass="int" keyProperty="id">select last_insert_id() as id</selectKey></insert><!-- 插入操作3 -->      <parameterMap class="User" id="pars">          <parameter property="name"/>          <parameter property="pwd"/>      </parameterMap>      <statement id="addUser3" parameterMap="pars">          insert into Users(name,pwd) values(?,?)      </statement>          <!-- 删除操作 -->    <delete id="delUser" parameterClass="int">    delete from Users where id=#id#    </delete>        <!-- 修改操作 -->    <update id="updateUser" parameterClass="User">    update Users set name=#name#,pwd=#pwd# where id=#id#    </update>    <!-- 修改操作 2-->    <parameterMap class="User" id="pars2">    <parameter property="name"/>    <parameter property="pwd"/>    <parameter property="id"/>    </parameterMap>    <update id="updateUser2" parameterMap="pars2">    update Users set name=?,pwd=? where id=?    </update></sqlMap></span></span>
User_mybatis.xml

<span style="font-size:14px;"><span style="font-size:14px;"><?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="uu"><!-- 登陆 --><select id="login" resultType="User" parameterType="User">select * from Users where name=#{name} and pwd=#{pwd}</select><!-- 查询所有 --><select id="getAll" resultType="User">select * from user</select><!-- 模糊查询 --><select id="getLike" resultType="User" parameterType="string">select * from Users where name like #{name}</select><!-- 添加        keyProperty="id"返回的不是id--><insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">insert into Users(name,pwd) values(#{name},#{pwd})</insert><!-- 删除 --><delete id="delUser" parameterType="int">delete from Users where id=#{id}</delete><!-- 修改 --><update id="updateUser" parameterType="User">update Users set name=#{name},pwd=#{pwd} where id=#{id}</update></mapper></span></span>
然后创建ibatis,mybatis以及springmvc相关的配置文件和数据库连接文件:

1,mybatis配置文件Configuration.xml

<span style="font-size:14px;"><span style="font-size:14px;"><?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><properties resource="db.properties"/>  <!-- 实体类 --><typeAliases><typeAlias type="com.entity.User" alias="User"/></typeAliases> <!-- 配置数据源相关的信息 --> <environments default="demo"> <environment id="demo"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value= "${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.userName}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>  <!-- 列出映射文件 --> <mappers> <mapper resource="com/entity/User_mybatis.xml"/> </mappers> </configuration></span></span>
2,ibatis配置文件SqlMapConfig.xml

<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE sqlMapConfig  PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"  "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  <sqlMapConfig>      <properties resource="db.properties"/>      <settings           cacheModelsEnabled="true"          enhancementEnabled="true"          lazyLoadingEnabled="true"          maxRequests="32"          maxSessions="10"          maxTransactions="5"          useStatementNamespaces="true"/>    <!--     <setting>元素 maxRequests:同时执行SQL预计的最大线程数。 maxSessions:同一时间内活动的最大session数。 maxTransactions:同时进入SqlMapClient.startTransaction()的最大线程数。 cacheModelsEnabled:全局性地启用和禁用SqlMapClient的所有缓存model。 lazyLoadingEnabled:全局性地启用或禁用SqlMapClient的所有延迟加载。 enhancementEnabled:全局性地启用或禁用运行时字节码增强,以优化访问JavaBean属性的性能,同时优化延迟加载的性能。 useStatementNamespaces:如果启用本属性,必须使用全限定名来引用mapped statement。Mapped statement的全限定名由sql-map的名称和mapped-statement的名称合成。     -->      <!--           5、<datasource>元素 <datasource>是<transactionManager>的一部分,为SQL Map数据源设置了一系列参数。目前SQL Map架构只提供了三个DataSourceFactory,也可以添加自己的实现。 SimpleDataSourceFactory:DataSource提供了一个基本的实现,适用于J2EE容器提供DataSource的情况。 DbcpDataSourceFactory:实现使用Jakarta DBCP(Database Connection Pool)的DataSource API提供连接池服务。适用于应用/Web容器不提供DataSource服务的情况,或执行一单独的应用。 JndiDataSourceFactory:在应用容器内部从JNDI Context中查找DataSource实现。当使用应用服务器,并且服务器提供了容器管理的连接池和相关DataSource实现的情况下,可以使用JndiDataSourceFactory。 6、<sqlMap>元素 <sqlMap>元素用于包括SQL Map映射文件和其他的SQL Map配置文件。每个SqlMapClient对象使用的所有SQL Map映射文件都要在此声明。映射文件作为stream resource从类路径或URL读入。            -->                   <transactionManager type="JDBC">          <dataSource type="SIMPLE">               <property name="JDBC.Driver" value="${jdbc.driverClassName}"/>               <property name="JDBC.ConnectionURL" value="${jdbc.url}"/>               <property name="JDBC.Username" value="${jdbc.userName}"/>               <property name="JDBC.Password" value="${jdbc.password}"/>          </dataSource>      </transactionManager>      <sqlMap resource="com/entity/User_ibatis.xml"/>  </sqlMapConfig>  </span></span>
3,数据库连接文件db.properties

<span style="font-size:14px;"><span style="font-size:14px;">jdbc.driverClassName=com.microsoft.jdbc.sqlserver.SQLServerDriverjdbc.url=jdbc\:microsoft\:sqlserver\://localhost\:1433;DatabaseName\=test;SelectMethod\=cursorjdbc.userName=sajdbc.password=shich</span></span>

4,springmvc配置文件applicationContext.xml   与上面三个配置文件放在一处,都在src目录下面

<span style="font-size:14px;"><span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 自动扫描com.mvc下的所有注解 --><context:component-scan base-package="com"/></beans></span></span>

然后在创建spring-servlet.xml文件,此文件放在WEB-INF下

<span style="font-size:14px;"><span style="font-size:14px;"><?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:p="http://www.springframework.org/schema/p"         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">   <context:annotation-config />         <!-- 把标记了@Controller注解的类转换为bean -->        <context:component-scan base-package="com.action" />    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />              <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"            p:prefix="view/" p:suffix=".jsp" />          </beans></span></span>

修改web.xml文件,添加如下代码

<span style="font-size:14px;"><span style="font-size:14px;"> <!-- springMVC -->   <servlet>  <servlet-name>springmvc</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>    <load-on-startup>1</load-on-startup>   </servlet>   <servlet-mapping>  <servlet-name>springmvc</servlet-name>  <url-pattern>*.do</url-pattern>  </servlet-mapping>     <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>  </context-param>    <listener>   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener></span></span>

在创建测试类(访问数据库类以及action类)

jdbc连接类(sqlserver2000数据库)

<span style="font-size:14px;"><span style="font-size:14px;">package com.dao;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class DBHelper {private static String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=test";private static String user="sa";private static String pwd="shich";public Connection getConnection(){Connection conn=null;try{Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");conn=DriverManager.getConnection(url, user, pwd);}catch(Exception e){e.printStackTrace();}return conn;}public void close(ResultSet rs,PreparedStatement ps,Connection conn){try{if(rs!=null){rs.close();}if(ps!=null){ps.close();}if(conn!=null){conn.close();}}catch(Exception e){e.printStackTrace();}}public static void main(String[] args) {DBHelper db=new DBHelper();System.out.println(db.getConnection());}}</span></span>
service类:

<span style="font-size:14px;"><span style="font-size:14px;">package com.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.dao.UserDao;import com.entity.User;@Servicepublic class UserService {@Autowiredprivate UserDao ud;//jdbc登录public User login_jdbc(String name, String pwd){return ud.login_jdbc(name, pwd);}//ibatis登录public User login_ibatis(String name, String pwd) {return ud.login_ibatis(name, pwd);}//Mybatis登录public User login_Mybatis(String name, String pwd) {return ud.login_Mybatis(name, pwd);}}</span></span>

dao类:

<span style="font-size:14px;"><span style="font-size:14px;">package com.dao;import java.io.Reader;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.springframework.stereotype.Repository;import com.dao.DBHelper;import com.entity.User;import com.ibatis.common.resources.Resources;import com.ibatis.sqlmap.client.SqlMapClient;import com.ibatis.sqlmap.client.SqlMapClientBuilder;@Repositorypublic class UserDao{//ibatisprivate static SqlMapClient sqlMap;private static Reader iReader;//Mybatisprivate static SqlSessionFactory sqlSessionFactory;private static Reader myReader;//获得ibatis与Mybatis连接static{//ibatistry{iReader=Resources.getResourceAsReader("SqlMapConfig.xml");sqlMap=SqlMapClientBuilder.buildSqlMapClient(iReader);}catch(Exception e){e.printStackTrace();}//Mybatistry{myReader=Resources.getResourceAsReader("Configuration.xml");sqlSessionFactory = new SqlSessionFactoryBuilder().build(myReader);}catch(Exception e){e.printStackTrace();}}//jdbc登录public User login_jdbc(String name, String pwd) {DBHelper db=new DBHelper();Connection conn=null;PreparedStatement ps=null;ResultSet rs= null;String sql="select * from Users where name=? and pwd=?";User user=null; try{conn=db.getConnection();ps=conn.prepareStatement(sql);ps.setString(1, name);ps.setString(2, pwd);rs=ps.executeQuery();if(rs.next()){user=new User();user.setId(rs.getInt("id"));user.setName(rs.getString("name"));user.setPwd(rs.getString("pwd"));}}catch(Exception e){e.printStackTrace();}finally{db.close(rs, ps, conn);}return user;}//ibatis登录public User login_ibatis(String name, String pwd) {User user=null;try{User us=new User(0,name,pwd);user=(User)sqlMap.queryForObject("login2", us);//多参数查�?}catch(Exception e){e.printStackTrace();}return user;}//Mybatis登录public User login_Mybatis(String name, String pwd) {SqlSession session=sqlSessionFactory.openSession();User user=null;try{user=(User)session.selectOne("uu.login", new User(0,name,pwd));}catch(Exception e){e.printStackTrace();}finally{session.close();}return user;}public static void main(String[] args) {UserDao ud=new UserDao();//User user=ud.login_ibatis("test", "123");User user=ud.login_Mybatis("test", "123");if(user!=null){System.out.println("成功");}else{System.out.println("失败");}}}</span></span>
action类(controller类):
<span style="font-size:14px;"><span style="font-size:14px;">package com.action;import javax.servlet.http.HttpServletRequest;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.entity.User;import com.service.UserService;@Controller@RequestMapping(value="user.do")public class UserControl {@Autowiredprivate UserService userService;//private HttpServletRequest request;@RequestMapping(params="method=login")public String login(HttpServletRequest request,Model model){String uname=request.getParameter("uname");String pwd=request.getParameter("pwd");User us=userService.login_ibatis(uname, pwd);//User us=userService.login_Mybatis(uname, pwd);//User us=userService.login_jdbc(uname, pwd);if(us==null){request.setAttribute("msg", "登陆失败,账号或密码错误。");model.addAttribute("user", us);return "login";}else{request.setAttribute("msg", uname);return "index";}}//@RequestMapping(value="test")@RequestMapping(params="test")public String test(Model model){System.out.println("test....");model.addAttribute("msg", "纯属测试。。");//传值到页面return "index";}}</span></span>

启动tomcat运行,没有错误则配置正确。

代码下载:http://download.csdn.net/detail/xiaosheng_papa/8090713



0 0
原创粉丝点击