zoukankan      html  css  js  c++  java
  • Mybatis select、insert、update、delete 增删改查操作

    MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。 MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索。MyBatis 可以使用简单的XML 或注解用于配置和原始映射,将接口和 Java 的 POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

    MyBatis下载:https://github.com/mybatis/mybatis-3/releases

    Mybatis实例

    对一个User表的CRUD操作:

    User表:

    复制代码
    -- ----------------------------
    -- Table structure for `user`
    -- ----------------------------
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `userName` varchar(50) DEFAULT NULL,
      `userAge` int(11) DEFAULT NULL,
      `userAddress` varchar(200) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
    INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
    INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
    INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
    INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');
    复制代码

    在Src目录下建一个mybatis的xml配置文件Configuration.xml

    复制代码
    <?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>
        <!-- mybatis别名定义 -->
        <typeAliases> 
            <typeAlias alias="User" type="com.mybatis.test.User"/> 
        </typeAliases> 
    
        <environments default="development">
            <environment id="development">
            <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
                </dataSource>
            </environment>
        </environments>
        
        <!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
        <mappers>
            <mapper resource="com/mybatis/test/User.xml"/>
        </mappers>
    </configuration>
    复制代码

    定义User mappers的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="com.mybatis.test.IUserOperation">
    
        <!-- select语句 -->
        <select id="selectUserByID" parameterType="int" resultType="User">
            select * from `user` where user.id = #{id}
        </select>
        
        <!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题-->
        <!-- <resultMap type="User" id="userResultMap">
            <id property="id" column="user_id"  />
            <result property="userName" column="user_userName"  />
            <result property="userAge" column="user_userAge"  />
            <result property="userAddress" column="user_userAddress"  />
        </resultMap> -->
        
        <!-- 返回list的select语句,注意 resultMap的值是指向前面定义好的 -->
        <!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">
            select * from user where user.userName = #{userName}
        </select> -->
        
        <select id="selectUsersByName" parameterType="string" resultType="User">
            select * from user where user.userName = #{userName}
        </select>
        
        <!--执行增加操作的SQL语句。id和parameterType分别与IUserOperation接口中的addUser方法的名字和参数类型一致。
        useGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;keyProperty="id"指定把获取到的主键值注入到User的id属性--> 
        <insert id="addUser" parameterType="User" 
            useGeneratedKeys="true" keyProperty="id"> 
            insert into user(userName,userAge,userAddress)  
                 values(#{userName},#{userAge},#{userAddress})  
        </insert>
        
        <update id="updateUser" parameterType="User" >
            update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
        </update>
        
        <delete id="deleteUser" parameterType="int">
            delete from user where id=#{id}
        </delete>
        
    </mapper>
    复制代码

    配置文件实现了接口和SQL语句的映射关系。selectUsersByName采用了2种方式实现,注释掉的也是一种实现,采用resultMap可以把属性和数据库列名映射关系定义好,property为类的属性,column是表的列名,也可以是表列名的别名!

    select 语句属性配置细节:

    属性描述取值默认
    id 在这个模式下唯一的标识符,可被其它语句引用    
    parameterType 传给此语句的参数的完整类名或别名    
    resultType 语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)    
    resultMap 引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)    
    flushCache 如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false true/false false
    useCache 如果设为true,则语句的结果集将被缓存。select 语句默认设为false true/false false
    timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定 正整数 未设置
    fetchSize 设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定 正整数 驱动器决定
    statementType statement,preparedstatement,callablestatement。预准备语句、可调用语句 STATEMENT、PREPARED、CALLABLE PREPARED
    resultSetType forward_only、scroll_sensitive、scroll_insensitive 只转发,滚动敏感,不区分大小写的滚动 FORWARD_ONLY、SCROLL_SENSITIVE、SCROLL_INSENSITIVE 驱动器决定

    useGeneratedKeys 告诉MyBatis 使用JDBC 的getGeneratedKeys 方法来获取数据库自己生成的主键(MySQL、SQLSERVER 等关系型数据库会有自动生成的字段)。默认:false true/false false
    keyProperty 标识一个将要被MyBatis设置进getGeneratedKeys的key 所返回的值,或者为insert 语句使用一个selectKey子元素。

    insert:

    <!-- 插入学生 -->  
    <insert id="insertStudent" parameterType="StudentEntity">  
            INSERT INTO STUDENT_TBL (STUDENT_ID,  
                                              STUDENT_NAME,  
                                              STUDENT_SEX,  
                                              STUDENT_BIRTHDAY,  
                                              CLASS_ID)  
                  VALUES   (#{studentID},  
                              #{studentName},  
                              #{studentSex},  
                              #{studentBirthday},  
                              #{classEntity.classID})  
    </insert>  
    • 1

    <!-- 删除学生 --> <delete id="deleteStudent" parameterType="StudentEntity"> DELETE FROM STUDENT_TBL WHERE STUDENT_ID = #{studentID} </delete>

    <!-- 查询学生list,根据入学时间  -->  
    <select id="getStudentListByDate"  parameterType="Date" resultMap="studentResultMap">  
        SELECT *  
          FROM STUDENT_TBL ST LEFT JOIN CLASS_TBL CT ON ST.CLASS_ID = CT.CLASS_ID  
         WHERE CT.CLASS_YEAR = #{classYear};      
    </select>  
    •  
    List<StudentEntity> studentList = studentMapper.getStudentListByClassYear(StringUtil.parse("2007-9-1"));  
    for (StudentEntity entityTemp : studentList) {  
        System.out.println(entityTemp.toString());  
    } 
    
    

    多参数的实现

    
    

    如果想传入多个参数,则需要在接口的参数上添加@Param注解。给出一个实例: 
    接口写法:

    public List<StudentEntity> getStudentListWhereParam(@Param(value = "name") String name, @Param(value = "sex") String sex, @Param(value = "birthday") Date birthdar, @Param(value = "classEntity") ClassEntity classEntity);  

    <!-- 查询学生list,like姓名、=性别、=生日、=班级,多参数方式 -->  
    <select id="getStudentListWhereParam" resultMap="studentResultMap">  
        SELECT * from STUDENT_TBL ST  
        <where>  
            <if test="name!=null and name!='' ">  
                ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{name}),'%')  
            </if>  
            <if test="sex!= null and sex!= '' ">  
                AND ST.STUDENT_SEX = #{sex}  
            </if>  
            <if test="birthday!=null">  
                AND ST.STUDENT_BIRTHDAY = #{birthday}  
            </if>  
            <if test="classEntity!=null and classEntity.classID !=null and classEntity.classID!='' ">  
                AND ST.CLASS_ID = #{classEntity.classID}  
            </if>  
        </where>  
    </select>  

    https://www.cnblogs.com/luxiaoxun/p/4035040.html
    
    
    
  • 相关阅读:
    二次开发注意
    LAMP集群项目五 nfs分发文件到服务器
    LAMP集群项目五 nfs存储的数据实时同步到backupserver
    LAMP集群项目五 项目备份
    LAMP集群项目五 部署NFS存储服务并设置WEB服务挂载
    LAMP集群项目四 安装apache、php及其插件
    iOS-单选cell的实现
    iOS-省市区选择的实现
    随机颜色的产生
    刷新轮的使用
  • 原文地址:https://www.cnblogs.com/youxin/p/7906298.html
Copyright © 2011-2022 走看看