分享

Spring3.05简单集成MyBatis3.03

 旭龙 2011-03-16
写的不好,砖拍轻点...
mybatis一直没有发布release版本。所以spring也坐着看。但是spring还是必须用啊。
1. Pojo & mapper配置
 view plaincopy to clipboardprint?
package cn.java.forum.domain;  
 
import java.io.Serializable;  
import java.util.Date;  
 
public class People implements Serializable{  
   
    private static final long serialVersionUID = 1L;  
 
    private int id;  
      
    private String username;  
      
    private String password;  
      
    private String realName;  
      
    private Date registerTime;  
 
    @Override 
    public String toString() {  
        return "< id:"+id+", username:"+username+", password:"+password+", realName:"+realName  
                 +", registerTime:"+registerTime.toLocaleString()+" >";  
    }  
      
    public int getId() {  
        return id;  
    }  
 
    public void setId(int id) {  
        this.id = id;  
    }  
 
    public String getUsername() {  
        return username;  
    }  
 
    public void setUsername(String username) {  
        this.username = username;  
    }  
 
    public String getPassword() {  
        return password;  
    }  
 
    public void setPassword(String password) {  
        this.password = password;  
    }  
 
    public String getRealName() {  
        return realName;  
    }  
 
    public void setRealName(String realName) {  
        this.realName = realName;  
    }  
 
    public Date getRegisterTime() {  
        return registerTime;  
    }  
 
    public void setRegisterTime(Date registerTime) {  
        this.registerTime = registerTime;  
    }  

package cn.java.forum.domain;
import java.io.Serializable;
import java.util.Date;
public class People implements Serializable{
 
 private static final long serialVersionUID = 1L;
 private int id;
   
    private String username;
   
    private String password;
   
    private String realName;
   
    private Date registerTime;
    @Override
    public String toString() {
     return "< id:"+id+", username:"+username+", password:"+password+", realName:"+realName
              +", registerTime:"+registerTime.toLocaleString()+" >";
    }
   
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getRealName() {
  return realName;
 }
 public void setRealName(String realName) {
  this.realName = realName;
 }
 public Date getRegisterTime() {
  return registerTime;
 }
 public void setRegisterTime(Date registerTime) {
  this.registerTime = registerTime;
 }
}
 
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8" ?> 
 
<!DOCTYPE mapper        
    PUBLIC "-////DTD Mapper 3.0//EN"        
    "http:///dtd/mybatis-3-mapper.dtd"> 
 
<mapper namespace="cn.java.forum.domain.mapper.PeopleMapper"> 
    <!--  
    <cache eviction="FIFO" flushInterval="30000" readOnly="true" size="512"></cache> 
    --> 
    
    <select id="allPeople" resultType="People"> 
        select * from People  
    </select> 
 
</mapper> 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper     
    PUBLIC "-////DTD Mapper 3.0//EN"     
    "http:///dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.java.forum.domain.mapper.PeopleMapper">
    <!--
    <cache eviction="FIFO" flushInterval="30000" readOnly="true" size="512"></cache>
    -->
 
    <select id="allPeople" resultType="People">
        select * from People
    </select>
</mapper>
 
2. mapper接口
view plaincopy to clipboardprint?
package cn.java.forum.domain.mapper;  
 
import java.util.List;  
 
import cn.java.forum.domain.People;  
 
public interface PeopleMapper {  
     List<People> allPeople();  

package cn.java.forum.domain.mapper;
import java.util.List;
import cn.java.forum.domain.People;
public interface PeopleMapper {
     List<People> allPeople();
}
 
3.service接口
view plaincopy to clipboardprint?
package cn.java.forum.domain.service;  
 
import java.util.List;  
 
import cn.java.forum.domain.People;  
 
public interface PeopleService {  
    List<People> allPeople();  

package cn.java.forum.domain.service;
import java.util.List;
import cn.java.forum.domain.People;
public interface PeopleService {
 List<People> allPeople();
}
 
4. service实现,mapper经过注入。
view plaincopy to clipboardprint?
package cn.java.forum.domain.service.impl;  
 
import java.util.List;  
 
import cn.java.forum.domain.People;  
import cn.java.forum.domain.mapper.PeopleMapper;  
import cn.java.forum.domain.service.PeopleService;  
 
public class PeopleServiceBean implements PeopleService{  
 
    /* 需要注入 */ 
    private PeopleMapper mapper;  
 
    public PeopleMapper getMapper() {  
        return mapper;  
    }  
 
    public void setMapper(PeopleMapper mapper) {  
        this.mapper = mapper;  
    }  
 
    @Override 
    public List<People> allPeople() {  
        return mapper.allPeople();  
    }  
 

package cn.java.forum.domain.service.impl;
import java.util.List;
import cn.java.forum.domain.People;
import cn.java.forum.domain.mapper.PeopleMapper;
import cn.java.forum.domain.service.PeopleService;
public class PeopleServiceBean implements PeopleService{
 /* 需要注入 */
 private PeopleMapper mapper;
 public PeopleMapper getMapper() {
  return mapper;
 }
 public void setMapper(PeopleMapper mapper) {
  this.mapper = mapper;
 }
 @Override
 public List<People> allPeople() {
  return mapper.allPeople();
 }
}
 
基本的代码完成之后。就是配置文件了。
---------------------------------------------------华丽的分割线---------------------------------------------------
1.完整的spring主配置文件,包含了事务,mapper,数据源等的配置
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?> 
 
<beans xmlns="http://www./schema/beans
    xmlns:aop="http://www./schema/aop
    xmlns:context="http://www./schema/context
    xmlns:tx="http://www./schema/tx
    xmlns:xsi="http://www./2001/XMLSchema-instance
    xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd http://www./schema/aop http://www./schema/aop/spring-aop-2.5.xsd http://www./schema/context http://www./schema/context/spring-context-2.5.xsd http://www./schema/tx http://www./schema/tx/spring-tx-2.5.xsd"> 
       
    <!-- ============================== 数据库配置 ==================================== --> 
    <!-- 数据源配置 --> 
    <bean name="dataSource" 
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <property name="driverClassName"> 
            <value>com.mysql.jdbc.Driver</value> 
        </property> 
        <property name="url"> 
            <value>jdbc:mysql://localhost:3306/forum</value> 
        </property> 
        <property name="username"> 
            <value>root</value> 
        </property> 
        <property name="password"> 
            <value>123456</value> 
        </property> 
    </bean> 
      
    <!-- ================================ MyBatis SqlSession配置 ========================================= --> 
    <!-- 使用SqlSessionFactoryBean工厂产生SqlSession对象,方便后期注入Dao --> 
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" /> 
        <property name="configLocation" value="classpath:Configuration.xml"></property> 
    </bean> 
   
    <!-- ================================= mapper ============================================= --> 
    <!-- 人员mapper --> 
    <bean id="peopleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/> 
        <!-- mapper的位置 --> 
        <property name="mapperInterface" value="cn.java.forum.domain.mapper.PeopleMapper"/> 
    </bean> 
      
    <!-- ================================= 事务控制相关 ============================================= --> 
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     
        <property name="dataSource" ref="dataSource"></property> 
    </bean>     
      
    <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
        <tx:attributes> 
            <tx:method name="delete*" propagation="REQUIRED" read-only="false"   
                       rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/> 
            <tx:method name="insert*" propagation="REQUIRED" read-only="false"   
                       rollback-for="java.lang.RuntimeException" /> 
            <tx:method name="update*" propagation="REQUIRED" read-only="false"   
                       rollback-for="java.lang.Exception" /> 
              
            <tx:method name="find*" propagation="SUPPORTS"/> 
            <tx:method name="get*" propagation="SUPPORTS"/> 
            <tx:method name="select*" propagation="SUPPORTS"/> 
        </tx:attributes> 
    </tx:advice>   
      
    <!-- 引入service层的spring配置 --> 
    <import resource="applicationContext-service.xml"/>   
</beans> 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
 xmlns:aop="http://www./schema/aop"
 xmlns:context="http://www./schema/context"
 xmlns:tx="http://www./schema/tx"
 xmlns:xsi="http://www./2001/XMLSchema-instance"
 xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd http://www./schema/aop http://www./schema/aop/spring-aop-2.5.xsd http://www./schema/context http://www./schema/context/spring-context-2.5.xsd http://www./schema/tx http://www./schema/tx/spring-tx-2.5.xsd">
    
    <!-- ============================== 数据库配置 ==================================== -->
 <!-- 数据源配置 -->
 <bean name="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName">
   <value>com.mysql.jdbc.Driver</value>
  </property>
  <property name="url">
   <value>jdbc:mysql://localhost:3306/forum</value>
  </property>
  <property name="username">
   <value>root</value>
  </property>
  <property name="password">
   <value>123456</value>
  </property>
 </bean>
 
 <!-- ================================ MyBatis SqlSession配置 ========================================= -->
 <!-- 使用SqlSessionFactoryBean工厂产生SqlSession对象,方便后期注入Dao -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" value="classpath:Configuration.xml"></property>
 </bean>
 
 <!-- ================================= mapper ============================================= -->
 <!-- 人员mapper -->
 <bean id="peopleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
  <!-- mapper的位置 -->
  <property name="mapperInterface" value="cn.java.forum.domain.mapper.PeopleMapper"/>
 </bean>
 
 <!-- ================================= 事务控制相关 ============================================= -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
     <property name="dataSource" ref="dataSource"></property>
  </bean>  
 
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="delete*" propagation="REQUIRED" read-only="false"
              rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/>
   <tx:method name="insert*" propagation="REQUIRED" read-only="false"
              rollback-for="java.lang.RuntimeException" />
   <tx:method name="update*" propagation="REQUIRED" read-only="false"
              rollback-for="java.lang.Exception" />
   
   <tx:method name="find*" propagation="SUPPORTS"/>
   <tx:method name="get*" propagation="SUPPORTS"/>
   <tx:method name="select*" propagation="SUPPORTS"/>
  </tx:attributes>
 </tx:advice>
 
 <!-- 引入service层的spring配置 -->
 <import resource="applicationContext-service.xml"/>
</beans>
2.MyBatis的配置文件,暂时只配置了 别名 和 mapper
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8" ?> 
 
<!DOCTYPE configuration        
    PUBLIC "-////DTD SQL Map Config 3.0//EN"        
    "http:///dtd/mybatis-3-config.dtd"> 
      
<configuration> 
   
    <typeAliases> 
         <typeAlias type="cn.java.forum.domain.Grade" alias="Grade"/> 
         <typeAlias type="cn.java.forum.domain.People" alias="People"/> 
         <typeAlias type="cn.java.forum.domain.Response" alias="Response"/> 
         <typeAlias type="cn.java.forum.domain.Topic" alias="Topic"/> 
    </typeAliases> 
      
    <!--  spring配置之后 这些就可以省略了  
    <environments default="development"> 
        <environment id="development"> 
            <transactionManager type="JDBC"> 
            </transactionManager> 
              
            <dataSource type="POOLED"> 
                <property name="driver" 
                    value="com.mysql.jdbc.Driver" /> 
                <property name="url" 
                    value="jdbc:mysql://localhost:3306/forum" /> 
                <property name="username" value="root" /> 
                <property name="password" value="123456" /> 
            </dataSource> 
        </environment> 
    </environments> --> 
      
    <mappers> 
        <mapper resource="cn/java/forum/domain/config/Grade.xml"/> 
        <mapper resource="cn/java/forum/domain/config/People.xml"/> 
        <mapper resource="cn/java/forum/domain/config/Response.xml"/> 
        <mapper resource="cn/java/forum/domain/config/Topic.xml"/> 
    </mappers> 
 
</configuration> 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration     
    PUBLIC "-////DTD SQL Map Config 3.0//EN"     
    "http:///dtd/mybatis-3-config.dtd">
   
<configuration>
 
    <typeAliases>
         <typeAlias type="cn.java.forum.domain.Grade" alias="Grade"/>
         <typeAlias type="cn.java.forum.domain.People" alias="People"/>
         <typeAlias type="cn.java.forum.domain.Response" alias="Response"/>
         <typeAlias type="cn.java.forum.domain.Topic" alias="Topic"/>
    </typeAliases>
   
    <!--  spring配置之后 这些就可以省略了
 <environments default="development">
  <environment id="development">
   <transactionManager type="JDBC">
   </transactionManager>
   
   <dataSource type="POOLED">
    <property name="driver"
     value="com.mysql.jdbc.Driver" />
    <property name="url"
     value="jdbc:mysql://localhost:3306/forum" />
    <property name="username" value="root" />
    <property name="password" value="123456" />
   </dataSource>
  </environment>
 </environments> -->
 
    <mappers>
        <mapper resource="cn/java/forum/domain/config/Grade.xml"/>
        <mapper resource="cn/java/forum/domain/config/People.xml"/>
        <mapper resource="cn/java/forum/domain/config/Response.xml"/>
        <mapper resource="cn/java/forum/domain/config/Topic.xml"/>
    </mappers>
</configuration>
 
3. service层的配置文件
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="UTF-8"?> 
 
<beans xmlns="http://www./schema/beans
    xmlns:aop="http://www./schema/aop
    xmlns:context="http://www./schema/context
    xmlns:tx="http://www./schema/tx
    xmlns:xsi="http://www./2001/XMLSchema-instance
    xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd http://www./schema/aop http://www./schema/aop/spring-aop-2.5.xsd http://www./schema/context http://www./schema/context/spring-context-2.5.xsd http://www./schema/tx http://www./schema/tx/spring-tx-2.5.xsd"> 
       
    <bean id="peopleService" class="cn.java.forum.domain.service.impl.PeopleServiceBean"> 
         <property name="mapper"> 
             <ref bean="peopleMapper"/> 
         </property> 
    </bean> 
</beans> 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
 xmlns:aop="http://www./schema/aop"
 xmlns:context="http://www./schema/context"
 xmlns:tx="http://www./schema/tx"
 xmlns:xsi="http://www./2001/XMLSchema-instance"
 xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd http://www./schema/aop http://www./schema/aop/spring-aop-2.5.xsd http://www./schema/context http://www./schema/context/spring-context-2.5.xsd http://www./schema/tx http://www./schema/tx/spring-tx-2.5.xsd">
    
    <bean id="peopleService" class="cn.java.forum.domain.service.impl.PeopleServiceBean">
         <property name="mapper">
             <ref bean="peopleMapper"/>
         </property>
    </bean>
</beans>
4.最后,是启动spring的配置 WEB.XML
view plaincopy to clipboardprint?
<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> 
 <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>
ok  写一个servlet来测试(其实类也可以的。)。
view plaincopy to clipboardprint?
package servlet;  
 
import java.io.IOException;  
import java.io.PrintWriter;  
 
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import org.springframework.context.ApplicationContext;  
import org.springframework.context.support.ClassPathXmlApplicationContext;  
 
import cn.java.forum.domain.service.PeopleService;  
 
public class TestServlet extends HttpServlet {  
 
    private static final long serialVersionUID = 1L;  
 
    public TestServlet() {  
        super();  
    }  
 
    public void destroy() {  
        super.destroy();  
    }  
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doPost(request, response);  
    }  
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
 
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
           
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");  
        PeopleService peopleService = (PeopleService) ctx.getBean("peopleService");  
        System.out.println("the list:"+peopleService.allPeople());  
        out.flush();  
        out.close();  
    }  
 
    public void init() throws ServletException {  
    }  
 
 
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sustbeckham/archive/2010/12/17/6082677.aspx

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多