MyBatis+Spring实现基本CRUD操作

一、MyBaits介绍
   MyBatis 是一个可以自定义SQL、存储过程和高级映射的持久层框架。MyBatis 摒除了大部分的JDBC代码、手工设置参数和结果集重获。MyBatis 只使用简单的XML 和注解来配置和映
射基本数据类型、Map 接口和POJO 到数据库记录。相对Hibernate和Apache OJB等“一站式”ORM解决方案而言,Mybatis 是一种“半自动化”的ORM实现。
   与hibernate对比,MyBatis更基础,要求使用者自己控制的东西更多。mybatis完成了基本的一些ORM概念,但是没有Hibernate那么完善。要使用mybatis,程序员的关注点更集中于SQL和数据库结构设计。mybatis没有hibernate使用起来那么面向对象,所以,在使用mybatis的时候,hibernate的一些思想和设计需要改变。

二、环境配置

  1、引入jar包

  2、配置web.xml


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring.xmlparam-value>
    context-param>

  3、编写连接数据配置文件 jdbc.properties

  4、编写spring.xml配置文件


    <context:property-placeholder location="classpath:jdbc.properties" />
    
    
    <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}" />
bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml">property>
    bean>
    
    
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    bean>
    
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    
    
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">bean>
    
    
    <bean id="userDao" class="com.mybaits.dao.impl.UserDaoImpl">
        <property name="sqlSessionTemplate" ref="sqlSessionTemplate">property>
    bean>
    
    

<bean id="userService" class="com.mybaits.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao">property> bean>

三、CRUD操作

  1、编写实体类User  

        private int id;
        private String username;
        private String usernumber;
        private String loginname;
        private String loginpassword;
        private String sex;
        private Date birthday;    
       //.......此处省略get/set方法

  2、Dao层接口及实现类

public interface IUserDao {
    
        public void addUser(User user);
        
        public void deleteUser(String usernumber);
        
        public void updateUser(User user);
        
        public User findUser(String usernumber);
        
        public List findUser();
}
public class UserDaoImpl implements IUserDao{
    
    private SqlSessionTemplate sqlSessionTemplate;
    
    
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public void addUser(User user) {
        // TODO Auto-generated method stub
        sqlSessionTemplate.insert("addUser", user);
    }

    @Override
    public void deleteUser(String usernumber) {
        // TODO Auto-generated method stub
        sqlSessionTemplate.delete("deleteUser",usernumber);
    }
    //........此处省略其他方法
//sqlSessionTemplate.delete("deleteUser",usernumber);其中"deleteUser"对应user.xml中,delete标签中的id,其他也类似
}

  3、创建User对象的sql语句映射文件,user.xml

<mapper namespace="com.mybaits.bean.User">
        <resultMap type="com.mybaits.bean.User" id="userResult">
            <id property="id" column="id" />
            <result property="username" column="username"/>
            <result property="usernumber" column="usernumber"/>
            <result property="loginname" column="loginname"/>
            <result property="loginpassword" column="loginpassword"/>
            <result property="sex" column="sex"/>
            <result property="birthday" column="birthday" />
        resultMap>
    
        <insert id="addUser" parameterType="User" >   
            insert into user (username,usernumber,loginname,loginpassword,sex,birthday) values(#{username},#{usernumber},#{loginname},#{loginpassword},#{sex},#{birthday})
        insert>
        <delete id="deleteUser" parameterType="String">
            delete from user where user.usernumber=#{usernumber}
        delete>
        
        <update id="updateUser" parameterType="User" >
            update user set username=#{username},loginname=#{loginname},loginpassword=#{loginpassword},sex=#{sex},birthday=#{birthday} where usernumber=#{usernumber}
        update>          
        <select id="findUserByUsernumber" parameterType="string" resultType="User">
            select * from user where usernumber = #{usernumber}       
        select>   
        <select id="findAllUser" resultType="User">
            select * from user
        select>
        <select id="findUserByName" parameterType="String" resultType="User">
            select * from user where usernumber like CONCAT(CONCAT('%', #{usernumber}), '%')
        select>
mapper>
   

  4、创建Mybaits的mapper配置文件mybaits.xml

  typeAliases:给类起别名

  mappers:加载实体类User的sql映射文件

<configuration>
    <typeAliases>
        <typeAlias type="com.mybaits.bean.User" alias="User"/>
    typeAliases>
    <mappers>
        <mapper resource="com/mybaits/dao/impl/user.xml" />
    mappers>
configuration>    

四、使用junit编写测试类

public class UserTest {
    
    private IUserService userService;
    private IUserDao userDao;

    @Before
    public void init(){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
        userService=(IUserService) ctx.getBean("userService");
        userDao=(IUserDao) ctx.getBean("userDao");
    }
    
    @Test
    public void Test(){
        User u=new User();
        u.setUsername("王一飞");
        u.setUsernumber("01111305");
        u.setLoginname("admin");
        u.setLoginpassword("admin");
        u.setSex("男");
        u.setBirthday(new Date());
        userDao.addUser(u);
    }

  @Test
    public void Test3(){
        User u=userService.findUser("01111001");
        System.out.println(u.getUsername());
    }
  //.....此处省略其他测试方法
}

 

转载于:https://www.cnblogs.com/nww57/p/4685814.html

你可能感兴趣的:(MyBatis+Spring实现基本CRUD操作)