MyBatis3.1.1+Spring3.1.1的增、删、查、改以及分页和事务管理

1. [代码]Mybatis3.1.1+Spring3.1.1+MySQL5.5     
实体bean
packagecom.pb.mybatis.entity;
 
publicclass User {
     
    Integer age; //年龄
    Integer gender;  //性别  
    Integer id;
    String mail; //邮箱
    String nickname;
    String password;
    String site; //个人站点
    String username;
    publicUser() {
        super();
        // TODO Auto-generated constructor stub
    }
    publicUser(Integer id) {
        super();
        this.id = id;
    }
    publicUser(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    publicUser(String password, String username, String nickname,
            Integer gender, Integer age, String mail, String site) {
        super();
        this.password = password;
        this.username = username;
        this.nickname = nickname;
        this.gender = gender;
        this.age = age;
        this.mail = mail;
        this.site = site;
    }
    publicUser(Integer id,Integer age, Integer gender, String mail,
            String nickname, String password, String site, String username) {
        super();
        this.age = age;
        this.gender = gender;
        this.id = id;
        this.mail = mail;
        this.nickname = nickname;
        this.password = password;
        this.site = site;
        this.username = username;
    }
    publicInteger getAge() {
        returnage;
    }
    publicInteger getGender() {
        returngender;
    }
    publicInteger getId() {
        returnid;
    }
    publicString getMail() {
        returnmail;
    }
    publicString getNickname() {
        returnnickname;
    }
    publicString getPassword() {
        returnpassword;
    }
    publicString getSite() {
        returnsite;
    }
    publicString getUsername() {
        returnusername;
    }
    publicvoid setAge(Integer age) {
        this.age = age;
    }
    publicvoid setGender(Integer gender) {
        this.gender = gender;
    }
    publicvoid setId(Integer id) {
        this.id = id;
    }
    publicvoid setMail(String mail) {
        this.mail = mail;
    }
    publicvoid setNickname(String nickname) {
        this.nickname = nickname;
    }
    publicvoid setPassword(String password) {
        this.password = password;
    }
    publicvoid setSite(String site) {
        this.site = site;
    }
    publicvoid setUsername(String username) {
        this.username = username;
    }
}
实体类的UserDao
packagecom.pb.mybatis.dao;
 
importjava.util.List;
importcom.pb.mybatis.entity.User;
importcom.pb.mybatis.util.UserPage;
/**
 * 定义实体内操作接口Dao
 * @author Voishion
 * @version 2012.12.30
 */
publicinterface UserDao {
     
    /**
     * 保存
     * @param user
     */
    voidsave(User user);
     
    /**
     * 查询所有
     * @return
     */
    List<User> findAll();
     
    /**
     * 按ID查询
     * @param id
     * @return
     */
    User findById(Integer id);
     
    /**
     * 删除
     * @param user
     */
    voiddelete(Integer id);
     
    /**
     * 更新
     * @param map
     */
    voidupdate(User user);
     
    /**
     * 分页查询
     * @param page
     * @return
     */
    List<User> findByPage(UserPage page);
     
    /**
     * 分页查询时得到符合条件的数据
     * @param page
     * @return
     */
    Integer getCount(UserPage page);
 
}
实体类UserDao的实现UserDaoImpl-----
 
packagecom.pb.mybatis.dao.impl;
 
importjava.util.List;
importcom.pb.mybatis.dao.UserDao;
importcom.pb.mybatis.entity.User;
importcom.pb.mybatis.mapper.UserMapper;
importcom.pb.mybatis.util.UserPage;
 
publicclass UserDaoImpl implementsUserDao{
     
    //在此处注入一个UserMapper
    privateUserMapper userMapper;
 
    publicvoid setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
 
    @Override
    publicvoid delete(Integer id) {
        userMapper.delete(id);
    }
 
    @Override
    publicList<User> findAll() {
        returnuserMapper.findAll();
    }
 
    @Override
    publicUser findById(Integer id) {
        returnuserMapper.findById(id);
    }
 
    @Override
    publicvoid save(User user) {
        userMapper.save(user);
//      throw new RuntimeException("Error");        
    }
 
    @Override
    publicvoid update(User user) {
        userMapper.update(user);       
    }
 
    @Override
    publicList<User> findByPage(UserPage page) {
        returnuserMapper.findByPage(page);
    }
 
    @Override
    publicInteger getCount(UserPage page) {
        returnuserMapper.getCount(page);
    }
}
我想大家现在都在关心UserDaoImpl中的UserMapper是从哪里来的:
 
首先我们需要一个分页查询的中间类UserPage:
 
packagecom.pb.mybatis.util;
 
importcom.pb.mybatis.entity.User;
 
/**
 * User 分页查询公共条件类
 * @author Voishion
 */
publicclass UserPage {
    Integer firstRec;
    Integer pageSize;
    User user;
    publicInteger getFirstRec() {
        returnfirstRec;
    }
    publicvoid setFirstRec(Integer firstRec) {
        this.firstRec = firstRec;
    }
    publicInteger getPageSize() {
        returnpageSize;
    }
    publicvoid setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }
    publicUser getUser() {
        returnuser;
    }
    publicvoid setUser(User user) {
        this.user = user;
    }  
}
其次就是UserMapper映射了~~~~~~~~
 
packagecom.pb.mybatis.mapper;
 
importjava.util.List;
importcom.pb.mybatis.entity.User;
importcom.pb.mybatis.util.UserPage;
 
/**
 * 定义实体内操作接口
 * @author Voishion
 * @version 2012.12.30
 */
publicinterface UserMapper {
    /**
     * 保存
     * @param user
     */
    voidsave(User user);
     
    /**
     * 查询所有
     * @return
     */
    List<User> findAll();
     
    /**
     * 按ID查询
     * @param id
     * @return
     */
    User findById(Integer id);
     
    /**
     * 删除
     * @param user
     */
    voiddelete(Integer id);
     
    /**
     * 更新
     * @param map
     */
    voidupdate(User user);
     
    /**
     * 分页查询
     * @param page
     * @return
     */
    List<User> findByPage(UserPage page);
     
    /**
     * 分页查询时得到符合条件的数据
     * @param page
     * @return
     */
    Integer getCount(UserPage page);
 
}
注意UserMapper要与在同一个包下的UserMapper.xml同名,且在同一包下:以下就是UserMapper的映射文件UserMapper.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">
         
<!-- Mapper文件最好放在与Dao接口同一目次下 -->
<mapper namespace="com.pb.mybatis.mapper.UserMapper">
   
  <!-- 定义数据库字段与实体对象的映射关系 -->
  <resultMap type="com.pb.mybatis.entity.User"id="resultUser">
    <id property="id"column="ID"/>
    <result property="age"column="AGE"/>
    <result property="gender"column="GENDER"/>
    <result property="mail"column="MAIL"/>
    <result property="nickname"column="NICKNAME"/>
    <result property="password"column="PASSWORD"/>
    <result property="site"column="SITE"/>
    <result property="username"column="USERNAME"/>
  </resultMap>
   
  <parameterMap type="com.pb.mybatis.entity.User"id="paramUser">
    <parameter property="id"/>
    <parameter property="age"/>
    <parameter property="gender"/>
    <parameter property="mail"/>
    <parameter property="nickname"/>
    <parameter property="password"/>
    <parameter property="site"/>
    <parameter property="username"/>
  </parameterMap>
   
  <!-- 定义要操纵的SQL语句 -->  
  <insert id="save"parameterType="com.pb.mybatis.entity.User">
    INSERT INTO user(id,age,gender,username,password,mail,nickname,site)
    VALUES(#{id},#{age},#{gender},#{username},#{password},#{mail},#{nickname},#{site})
  </insert>
   
  <select id="findAll"resultMap="resultUser">
    SELECT * FROM user
  </select>
   
  <select id="findById"parameterType="Integer"resultMap="resultUser">
    SELECT * FROM user
    WHERE id=#{value}
  </select>
   
  <delete id="delete"parameterType="Integer">
    DELETE FROM user 
    WHERE id=#{value}
  </delete>
   
  <update id="update"parameterType="com.pb.mybatis.entity.User">
    UPDATE user
    <set>
       <iftest="age != null">age=#{age},</if>
       <iftest="gender != null">gender=#{gender},</if>
       <iftest="username != null">username=#{username},</if>
       <iftest="password != null">password=#{password},</if>
       <iftest="mail != null">mail=#{mail},</if>
       <iftest="nickname != null">nickname=#{nickname},</if>
       <iftest="site != null">site=#{site},</if>
    </set>
    WHERE id=#{id}
  </update>
   
  <select id="findByPage"parameterType="com.pb.mybatis.util.UserPage"resultMap="resultUser">
    SELECT * FROM user
    WHERE1=1
    <iftest="user != null">
       <iftest="user.nickname != null">and nickname like #{user.nickname}</if>
       <iftest="user.username != null">and username like #{user.username}</if>      
    </if>   
    LIMIT #{firstRec},#{pageSize}   
  </select>
   
  <select id="getCount"parameterType="com.pb.mybatis.util.UserPage"resultType="Integer">
    SELECT count(*) FROM user
    WHERE1=1
    <iftest="user != null">      
       <iftest="user.nickname != null">and nickname like #{user.nickname}</if>
       <iftest="user.username != null">and username like #{user.username}</if>      
    </if>   
  </select>
</mapper>
现在是UserService业务层:
 
packagecom.pb.mybatis.service;
 
importjava.util.List;
 
importcom.pb.mybatis.entity.User;
importcom.pb.mybatis.util.UserPage;
 
/**
 * Service层User操作接口
 * @author Voishion
 * @version 2012.12.30
 */
publicinterface UserService {
     
    voidsaveUser(User user);
 
    voidupdateUser(User user);
     
    voiddeleteUser(Integer id);
     
    User findById(Integer id);
     
    List<User> findAll();
     
    List<User> findByPage(UserPage page);
     
    Integer getCount(UserPage page);
}
UserServiceImpl实现:
 
packagecom.pb.mybatis.service.impl;
 
importjava.util.List;
importcom.pb.mybatis.dao.UserDao;
importcom.pb.mybatis.entity.User;
importcom.pb.mybatis.service.UserService;
importcom.pb.mybatis.util.UserPage;
/**
 * Service层User操作接口实现
 * @author Voishion
 * @version 2012.12.30
 */
publicclass UserServiceImpl implementsUserService{
 
    privateUserDao userDao;
     
    publicvoid setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
 
    @Override
    publicvoid saveUser(User user) {
        userDao.save(user);    
    }
 
    @Override
    publicvoid deleteUser(Integer id) {
        userDao.delete(id);
         
    }
 
    @Override
    publicvoid updateUser(User user) {
        userDao.update(user);      
    }
 
    @Override
    publicList<User> findAll() {
        returnuserDao.findAll();
    }
 
    @Override
    publicUser findById(Integer id) {
        returnuserDao.findById(id);
    }
 
    @Override
    publicList<User> findByPage(UserPage page) {
        returnuserDao.findByPage(page);
    }
 
    @Override
    publicInteger getCount(UserPage page) {
        returnuserDao.getCount(page);
    }
 
}

注意,以下就是spring的applicationContext.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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  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/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
          
  <!-- 将所有的配置文件没有放在外面:简单,但可维护性不高 -->
   
  <context:annotation-config/>
  <!-- 扫描物理路径及注册 --> 
  <context:component-scan base-package="com.pb.mybatis.*"/>
   
  <!-- jdbc.properties Directory -->
  <beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="locations"value="classpath:jdbc.properties"/>
  </bean>
  <bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName"value="${jdbc.driverClassName}"/>
     <property name="url"value="${jdbc.url}"/>
     <property name="username"value="${jdbc.username}"/>
     <property name="password"value="${jdbc.password}"/>
  </bean>
 
  <!-- SqlSessionFactory -->
  <bean id="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource"ref="dataSource"/>
  </bean>
   
  <!-- ScanMapperFiles -->
  <beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage"value="com.pb.mybatis.mapper"/>
  </bean>
   
  <!-- TransactionManager Contorl-->
  <bean name="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     <property name="dataSource"ref="dataSource"/>
  </bean>
  <tx:advice id="userTxAdvice"transaction-manager="transactionManager">
     <tx:attributes>
        <tx:method name="save*"propagation="REQUIRED"read-only="false"rollback-for="java.lang.Exception"no-rollback-for="java.lang.RuntimeException"/>
        <tx:method name="delete*"propagation="REQUIRED"read-only="false"rollback-for="java.lang.Exception"no-rollback-for="java.lang.RuntimeException"/>
        <tx:method name="update*"propagation="REQUIRED"read-only="false"rollback-for="java.lang.Exception"no-rollback-for="java.lang.RuntimeException"/>
        <tx:method name="find*"propagation="SUPPORTS"read-only="true"/>
     </tx:attributes> 
  </tx:advice>
  <aop:config>
     <!--把事务控制在Service层-->
     <aop:pointcut id="pc"expression="execution(* com.pb.mybatis.service.*.*(..))"/>
     <aop:advisor advice-ref="userTxAdvice"pointcut-ref="pc"/>
  </aop:config>
   
  <!-- Dao Bean-->
  <bean id="userDao"class="com.pb.mybatis.dao.impl.UserDaoImpl"autowire="byName"/>
   
  <!-- Service Bean -->
  <bean id="userService"class="com.pb.mybatis.service.impl.UserServiceImpl"autowire="byName"/>
</beans>
还有一个就是JDBC.properties配置文件:
 
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/blog
jdbc.username=root
jdbc.password=12345
 
项目目录结构:
2. [图片] Mybatis.jpg    

举报



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值