五、jdbcConfig.properties文件的编写以及别名typeAliases和package的使用

首先在resource路径下创建jdbcConfig.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

mybatis配置文件中的代码



<configuration>
    
    <properties resource="jdbcConfig.properties"/>
    
    <typeAliases>
        
        <package name="com.lp.domain"/>
    typeAliases>

    <environments default="localhost">
        <environment id="localhost">
            <transactionManager type="JDBC"/>
            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>

    <mappers>
        
        
        <package name="com.lp.dao"/>
    mappers>
configuration>

映射文件中的代码(使用了包别名后,可以直接用类型来调用,不区分大小写,比如User,USer,uSEr…都可以)



<mapper namespace="com.lp.dao.UserDao">

    <resultMap id="userMap" type="UsEr">
        <id property="userId" column="id"/>
        <result property="userName" column="username"/>
        <result property="userBirthday" column="birthday"/>
        <result property="userSex" column="sex"/>
        <result property="userAddress" column="address"/>
    resultMap>


    <select id="findAll"  resultMap="userMap">
        
        select * from user ;
    select>

    <insert id="saveUser" parameterType="User">
        insert into user
         (id,username,birthday,sex,address)
        values
         (#{userId},#{userName},#{userBirthday},#{userSex},#{userAddress});
    insert>

    <delete id="deleteUserById" parameterType="int">
        delete from user where id = #{id};
    delete>

    <update id="updateUser" parameterType="com.lp.domain.User">
        update user
        set
        username = #{userName},birthday=#{userBirthday},sex=#{userSex},address=#{userAddress}
        where id = #{userId};
    update>

    <select id="selectUserById" parameterType="int"  resultMap="userMap">
        select * from user where id = #{id };
    select>

    <select id="selectByLike" parameterType="String"  resultMap="userMap">
        

        select * from user where username like '%${username}%';
    select>

    <select id="selectUserCount" resultType="int">
        select count(id) from user ;
    select>

mapper>

你可能感兴趣的:(MyBatis)