码迷,mamicode.com
首页 > 编程语言 > 详细

mybatis整合spring

时间:2017-07-31 12:30:31      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:incr   parameter   turn   scanner   bsp   连接   ext.get   asi   2.x   

先创建工程,导入jar包

所需要的jar包

技术分享

配置文件

技术分享

SqlMapConfig.xml  是mybatis必须的配置文件

<?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>
        <typeAliases>
             <!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感) -->
            <package name="com.baoyuan.mybatis"/>
        </typeAliases>
        <!--使用传统的dao方式需要的配置,使用mapper接口无需配置  -->
        <mappers>
        <!-- 使用加载classpath底下的文件  加载sql映射文件-->
        <mapper resource="sqlmap/User.xml"/>
    </mappers>
</configuration>

applicationContext.xml 是spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-4.2.xsd">

    <!-- 加载连接的配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- dbcp数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    
    <!--配置sessionFactory  -->
    <bean  id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <!--name必须和 org.mybatis.spring.SqlSessionFactoryBean类中的bean属性名字一致 
                    ref:和上面定义的数据源id一致
                -->
        <property name="dataSource"  ref="dataSource"></property> 
        <!--name必须和 org.mybatis.spring.SqlSessionFactoryBean类中的bean属性名字一致 
                    value:mybatis的全局配置文件SqlMapConfig.xml的位置
        -->
        <property name="configLocation"  value="classpath:mybatis/SqlMapConfig.xml"></property>
    </bean>
    
    <!--使用传统Dao开发配置 -->
        <!--配置baseDao  -->
        <!-- 添加扫描组件的配置 扫描实现类所在的包或者其父包即可。 -->
        <context:component-scan base-package="com.baoyuan.mybatis.dao"/>
        <!--这样配每个dao都要配置太麻烦用上面的扫描包  -->
        <!-- <bean id="userDao" class="com.baoyuan.mybatis.dao.impl.UserDaoImpl">
            <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
        </bean> -->
    
    
    <!--使用mapper接口方式  -->
    <!--创建 mapper的代理对象交给spring管理  使用这种方式每个mapper都要配置,麻烦,用下面包扫描的方式 -->
    <!-- <bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="userMapper">
        <property name="mapperInterface"  value="com.baoyuan.mybatis.dao.mapper.UserMapper" ></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> 
    </bean> -->
    <!-- 使用扫描包的形式来创建mapper代理对象  , 每个mapper代理对象的id就是类名,首字母小写-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.baoyuan.mybatis.dao.mapper"></property>
    </bean>
</beans>

db.properties  连接数据库的配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123

user.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 namespace="test">
    <select id="findUserById" resultType="user"  parameterType="int" >
        select * from user where id =#{id}
    </select>
    <select id="findUserByUsername" resultType="user"  parameterType="java.lang.String">
        select * from user where username like ‘%${value}%‘
    </select>
    <insert id="saveUser"  parameterType="user">
        <!--配置在插入一条数据后返回主键,会自动保存到pojo对象的主键属性中  -->
        <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER"> 
            select LAST_INSERT_ID()
            <!--必须是主键自增长 是mysql的函数,返回auto_increment自增列新记录id值 -->
        </selectKey>
        insert INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
    </insert>
    <delete id="deleteUserById"  parameterType="int">
        delete from user where id =#{id}
    </delete>
    <update id="updateUserById" parameterType="user">
    UPDATE `user`
        <!-- 自动去掉多余, -->
        <set>
            <if test="username!=null and username!=‘‘">
                username = #{username},
            </if>
            <if test="sex!=null and sex!=‘‘">
                sex = #{sex},
            </if>
            <if test="birthday!=null">
                birthday= #{birthday},
            </if>
            <if test="address!=null and address!=‘‘">
                address = #{address},
            </if>
        </set>
        WHERE
        id = #{id}
    </update>
</mapper>

 

 

使用传统dao的方式

1.先提取公用的BaseDaoImpl,将sqlSessionFactory注入到父类的SqlSessionDaoSupport,以后dao都继承baseDaoImpl就不用在注入了

package com.baoyuan.mybatis.dao.base;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
/**
 * 持久层的通用接口,
 * 将sqlsessionFactory传给父类SqlSessionDaoSupport,
 * 让其余的dao继承,就不用每个dao都去传sqlsessionFactory
 * @author Administrator
 *
 */
@Repository
public class BaseDaoImpl  extends SqlSessionDaoSupport{
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }
}

2.编写dao层的接口IUserDao

package com.baoyuan.mybatis.dao;

import java.util.List;

import com.baoyuan.mybatis.pojo.User;


public interface IUserDao {
    //根据Id查询用户
    public User findUserById(Integer id);
    //根据用户名模糊查询用户
    public List<User> findUserByUsername(String username);
    //添加用户
    public void saveUser(User user);
    //根据id删除用户
    public void deleteUserById(Integer id);
    //更新用户
    public void updateUserById(User user);
}

3.编写实现类,同时继承通用Dao,注意,由于继承了SqlSessionDaoSupport,所以提交还有关闭资源都已经做了 ,只需要调用方法就可以了,不需要再进行提交和资源的关闭

package com.baoyuan.mybatis.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;

import com.baoyuan.mybatis.dao.IUserDao;
import com.baoyuan.mybatis.dao.base.BaseDaoImpl;
import com.baoyuan.mybatis.pojo.User;
/**
 * 用户操作的Daos实现类
 * @author Administrator
 *
 */
@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl implements IUserDao {
    
    
    //注意继承了SqlSessionDaoSupport,不用自己提交事务,也不用自己关闭资源
    public User  findUserById(Integer id){ 
        SqlSession session = super.getSqlSession();
        User user = session.selectOne("findUserById", id); 
        return user;
    }
    //根据用户名模糊查询用户
    public List<User> findUserByUsername(String username) { 
            return super.getSqlSession().selectList("test.findUserByUsername", username); 
    }
    //添加用户
    public void saveUser(User user) {
            super.getSqlSession().insert("saveUser", user);
        
    }
    //根据id删除用户
    public void deleteUserById(Integer id) {
            super.getSqlSession().delete("deleteUserById", id);
    }
    //更新用户
    public void updateUserById(User user) {
        getSqlSession().update("updateUserById", user);
    }
}    

测试传统dao代码

package com.baoyuan.test;

import java.util.Date;
import java.util.List;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.baoyuan.mybatis.dao.IUserDao;
import com.baoyuan.mybatis.pojo.User;
/**
 * 测试传统dao
 * @author Administrator
 *
 */
public class TestDao {
    
    //通过Id查询用户
    @Test
    public void findUserById(){ 
        ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        IUserDao bean = (IUserDao) cpac.getBean("userDao");
        User user = bean.findUserById(1);
        System.out.println(user); 
    }
    //通过用户名模糊查询用户
    @Test
    public void findUserByUsername(){ 
        ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        IUserDao bean = (IUserDao) cpac.getBean("userDao");
        List<User> list = bean.findUserByUsername("张") ;
        System.out.println(list); 
    }
    //添加用户
    @Test
    public void saveUser(){ 
        ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        IUserDao bean = (IUserDao) cpac.getBean("userDao");
        User user=new User();
        user.setUsername("牛杨");
        user.setSex("1");
        user.setAddress("长沙");
        user.setBirthday(new Date());
         bean.saveUser(user);
         System.out.println(user.getId()); 
    }
    //修改用户
    @Test
    public void updateUserById(){ 
        ClassPathXmlApplicationContext cpac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        IUserDao bean = (IUserDao) cpac.getBean("userDao");
        User user=new User();
        user.setId(25); 
        user.setUsername("牛");
        user.setSex("1");
        user.setAddress("长沙");
        user.setBirthday(new Date());
        bean.updateUserById(user);
    }
}

通过mapper接口方式(推荐)

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 namespace="com.baoyuan.mybatis.dao.mapper.UserMapper">
    <select id="findUserById" parameterType="int" resultType="user">
        select
        * from user where id =#{id}
    </select>
    <select id="findUserByusername" parameterType="java.lang.String"
        resultType="user">
        select * from user where username like ‘%${value}%‘
    </select>

    <select id="findUserByWhere" parameterType="user" resultType="user">
        select * from user
        <!-- where 自动去掉第一个and -->
        <where>
            <!--判断然后添加条件 -->
            <if test="id != null and id != ‘‘">
                and id =#{id}
            </if>
            <if test="username != null and username != ‘‘">
                and username like ‘%${username}%‘
            </if>
        </where>
    </select>



    <select id="findUserByAll" resultType="user">
        <!--include 表示运哪个sql片段 注意:如果引用其它mapper.xml的sql片段,则在引用时需要加上namespace,如下:<include 
            refid="namespace.sql片段”/> -->
        <include refid="query_all" />
        user
    </select>
    <!--sql片段的抽取 -->
    <sql id="query_all">
        select * from
    </sql>

    <!--set自动去掉多余的,为null和‘‘就不进行更新 -->
    <update id="updateUserByWhere" parameterType="user">
        UPDATE `user`
        <set>
            <if test="username!=null and username!=‘‘">
                username = #{username},
            </if>
            <if test="sex!=null and sex!=‘‘">
                sex = #{sex},
            </if>
            <if test="address!=null and address!=‘‘">
                address = #{address},
            </if>
        </set>
        WHERE
        id = #{id}
    </update>
    
    <insert id="saveUser"  parameterType="user">
        <!--配置在插入一条数据后返回主键,会自动保存到pojo对象的主键属性中  -->
        <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER"> 
            select LAST_INSERT_ID()
            <!--必须是主键自增长 是mysql的函数,返回auto_increment自增列新记录id值 -->
        </selectKey>
        insert INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
    </insert>
    <delete id="deleteUserById"  parameterType="int">
        delete from user where id =#{id}
    </delete>
</mapper>

UserMapper接口

package com.baoyuan.mybatis.dao.mapper;

import java.util.List;

import com.baoyuan.mybatis.pojo.User;
/**
 * 用户操作的mapper接口
 * @author Administrator
 *
 */
public interface UserMapper {
    public User findUserById(Integer id);
    
    public List<User> findUserByusername(String username); 
    
    public  List<User> findUserByWhere(User user);
    
    //查询所有
    public List<User> findUserByAll();
    
    public void updateUserByWhere(User user);
    
    public void saveUser(User user);
    
    public  void  deleteUserById(Integer id);
}

测试代码

package com.baoyuan.test;

import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.baoyuan.mybatis.dao.mapper.UserMapper;
import com.baoyuan.mybatis.pojo.User;

public class TestMapper {
    private ApplicationContext applicationContext;
    @Before
    public void init(){
        applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
    }
    //通过id查询用户
    @Test
    public void findUserById(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        User user = bean.findUserById(1);
        System.out.println(user);
    }
    //查询所有用户
    @Test
    public void findUserByAll(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        List<User> list = bean.findUserByAll();
        System.out.println(list);
    }
    //通过用户名模糊查询
    @Test
    public void findUserByusername(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        List<User> list = bean.findUserByusername("张"); 
        System.out.println(list);
    }
    //修改用户
    @Test
    public void updateUserByWhere(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        User user=new User();
        user.setId(28);
        user.setUsername("赵六"); 
        bean.updateUserByWhere(user);
    }
    //添加用户
    @Test
    public void saveUser(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        User user=new User();
        user.setUsername("周七");
        user.setSex("2");
        user.setBirthday(new Date());
        user.setAddress("岳阳");
        bean.saveUser(user);
    }
    //删除用户
    @Test
    public void deleteUserById(){
        UserMapper bean = applicationContext.getBean(UserMapper.class);
        bean.deleteUserById(29);;
    }
}

 

mybatis整合spring

标签:incr   parameter   turn   scanner   bsp   连接   ext.get   asi   2.x   

原文地址:http://www.cnblogs.com/jiangxiangit/p/7262380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!