其他分享
首页 > 其他分享> > Mybatis学习02_文件配置

Mybatis学习02_文件配置

作者:互联网

第一,导入jar包(方式很多,用一种)

mybatis核心包(必导)

数据库驱动包(必导)

第二,进行配置

1.mybatis-config.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>
    <!--
    在实际的开发过程中,我们可能分为开发环境,生产环境,测试环境等等,每个环境的配置可以是不一样的.
    每一个环境中都需要一个事务管理器和数据源的配置
    项目开发中几乎都是使用spring中配置的数据源和事务管理器来配置
    -->
    <!-- 标签的配置是有顺序的-->
    <properties resource="db.properties">
    </properties>

    <!-- mybatis的系统设置,很多属性可以设置-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"></setting>
    </settings>

    <!-- 设置别名-->
    <typeAliases>
        <!-- 第一种:单独配置-->
        <!--<typeAlias alias="SysUser" type="com.noma.entity.Sysuser"/>-->
        <package name="com.noma.entity"></package>
    </typeAliases>

    <!--default:用来选择需要的环境-->
    <environments default="dev">
        <!--id:表示不同环境的标识-->
        <!--开发环境-->
        <environment id="dev">
            <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>

        <!--开发环境-->
        <environment id="test">
            <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>
        <!-- 第一种方式:单独配置xml文件-->
        <!--<mapper resource="com/noma/mapper/SysuserMapper.xml"/>-->
        <!-- 第二种方式:单独配置类名-->
        <!--<mapper class="com.noma.mapper.SysroleMapper"/>-->
        <!-- 第三种方式:全局配置,包扫描-->
        <package name="com.noma.mapper"></package>
    </mappers>
</configuration>

2.SysuserMapper.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.noma.mapper.SysuserMapper">
    <cache
            eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"
    />

    <select id="selectList" resultType="com.noma.entity.Sysuser">
        select * from sysuser
    </select>
    <select id="findById" resultType="com.noma.entity.Sysuser">
        select * from sysuser where uid = #{uid}
    </select>

    <insert id="insertUser">
      insert into sysuser(uname, upwd) values (#{uname},#{upwd})
    </insert>

    <update id="updateUser" flushCache="true">
        update sysuser
         <set>
             <if test="uname != null and uname != ''">
                 ,uname = #{uname}
             </if>
            <if test="upwd != null and upwd != ''">
             ,upwd = #{upwd}
            </if>
         </set>
         where uid = #{uid}
    </update>

    <delete id="deleteUser">
        delete from sysuser where uid = #{uid}
    </delete>

    <insert id="addUser" keyProperty="uid" useGeneratedKeys="true">
        insert into sysuser(uname, upwd) values (#{uname},#{upwd} )
    </insert>

    <select id="findLikeUserName" resultType="com.noma.entity.Sysuser">
       select * from sysuser where uname like '%' #{uname} '%'
    </select>

    <select id="findByParams" resultType="com.noma.entity.Sysuser">
        select * from sysuser where uname like '%' #{name} '%' and upwd like '%' #{password} '%'
    </select>

    <select id="findByMap" parameterType="hashmap" resultType="com.noma.entity.Sysuser">
        select * from sysuser where uname like '%' #{name} '%' and upwd like '%' #{upwd} '%'
    </select>

    <select id="findByQueryEntity" parameterType="com.noma.entity.QueryEntity" resultType="com.noma.entity.Sysuser">
        select
         <include refid="allColumn"></include>
         from sysuser
        <where>
            <if test="uname != null and uname != ''">
                and uname like '%' #{uname} '%'
            </if>
            <if test="password != null and password != ''">
                and upwd like '%' #{password} '%'
            </if>
        </where>

        order by update_time desc
    </select>

    <select id="findBySorted" resultType="com.noma.entity.Sysuser">
        select *  from sysuser order by ${sortedColumn} ${sorted}
    </select>

    <!-- resultMap :可以解决数据库字段(含下划线) 与实体类中属性不一致,封装不上的问题-->
    <resultMap id="sysuserMap" type="com.noma.entity.Sysuser">
        <!--id 必须配置,其他数据库中字段与实体类一致的可以不配置,但是习惯上我们都配置-->
        <id column="uid" property="uid"></id>
        <result column="upwd_" property="upwd"></result>
    </resultMap>

    <resultMap id="userContainRoleMap" type="com.noma.entity.Sysuser">
        <id column="uid" property="uid"></id>
        <result column="uname" property="uname"></result>
        <result column="upwd" property="upwd"></result>
        <result column="uemail" property="uemail"></result>
        <result column="create_time" property="createTime"></result>
        <result column="update_time" property="updateTime"></result>
        <result column="phone" property="phone"></result>
        <result column="deleted" property="deleted"></result>
        <result column="rid" property="rid"></result>
        <association property="sysrole" column="rid" javaType="com.noma.entity.Sysrole" select="com.noma.mapper.SysroleMapper.findById"></association>
    </resultMap>

    <select id="findUserContainRoleByUid" resultMap="userContainRoleMap">
        select * from  sysuser where uid = #{uid}
    </select>

    <!--<select id="findUsersByRid" resultType="com.noma.entity.Sysuser">-->
        <!--select * from sysuser where rid = #{rid}-->
    <!--</select>-->

    <!--动态sql(标签的使用)-->
    <sql id="allColumn">
        uid,uname, upwd, uemail, phone, create_time, update_time, deleted, rid
    </sql>

    <sql id="commonColumn">
        uname,upwd
    </sql>

    <select id="findUsersByRid" resultType="com.noma.entity.Sysuser">
        select
        <include refid="allColumn"></include>
         from sysuser where rid = #{rid}
    </select>

    <delete id="deleteUserByIdList">
        delete from sysuser
        where uid in
        <foreach collection="collection" open="(" close=")" separator="," item="uid">
            #{uid}
        </foreach>
    </delete>

    <delete id="deleteUserByIds">
        delete from sysuser
        where uid in
        <foreach collection="aaa" open="(" close=")" separator="," item="uid">
            #{uid}
        </foreach>
    </delete>

    <insert id="batchtInsertUser">
        insert into
        sysuser (uname,phone) values
         <foreach collection="list" separator="," item="user">
             (#{user.uname},#{user.phone})
         </foreach>
    </insert>

</mapper>
View Code

3.UserMapperTest.java  测试类

  1 package com.noma.test;
  2 
  3 import com.noma.entity.QueryEntity;
  4 import com.noma.entity.Sysuser;
  5 import com.noma.mapper.SysroleMapper;
  6 import com.noma.mapper.SysuserMapper;
  7 import org.apache.ibatis.io.Resources;
  8 import org.apache.ibatis.session.SqlSession;
  9 import org.apache.ibatis.session.SqlSessionFactory;
 10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 11 import org.junit.*;
 12 import org.junit.runners.MethodSorters;
 13 
 14 import java.io.IOException;
 15 import java.io.InputStream;
 16 import java.util.ArrayList;
 17 import java.util.HashMap;
 18 import java.util.List;
 19 
 20 /**
 21  * @Author:wenjie
 22  * @Version:1.0
 23  * @Date:2022/2/15-21:35
 24  * @Since:jdk1.8
 25  * @Description:
 26  */
 27 
 28 
 29 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 30 public class UserApiTest {
 31 
 32     private static InputStream inputStream = null;
 33     private static SqlSessionFactory sqlSessionFactory = null;
 34     private SqlSession sqlSession = null;
 35 
 36     @BeforeClass
 37     public static void init(){
 38         //1加载(读取) 配置文件(一个核心文件&&映射文件)
 39         String resource = "com/noma/mybatis-config.xml";
 40 
 41         //2使用Resources工具类将配置文件转换成输入流对象
 42         try {
 43             inputStream = Resources.getResourceAsStream(resource);
 44         } catch (IOException e) {
 45             e.printStackTrace();
 46         }
 47 
 48         //3.SqlSessionFactoryBuilder根据流对象创建sqlSessionFactory
 49         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 50     }
 51 
 52     @AfterClass
 53     public static void destory(){
 54         if(inputStream!=null){
 55             try {
 56                 inputStream.close();
 57             } catch (IOException e) {
 58                 e.printStackTrace();
 59             }
 60         }
 61     }
 62 
 63     @Before
 64     public void openSession(){
 65         //4.sqlSessionFactory 创建sqlSession
 66          sqlSession = sqlSessionFactory.openSession();
 67     }
 68 
 69     @After
 70     public void closeSession(){
 71         if(sqlSession!=null){
 72             //事务
 73             sqlSession.commit();
 74             //关闭sqlSession
 75             sqlSession.close();
 76         }
 77     }
 78 
 79 
 80     @Test
 81     public void test1_User() throws IOException {
 82         //5.执行SQL语句:定位待要执行的SQL语句
 83         List<Sysuser> sysuserList = sqlSession.selectList("com.noma.mapper.SysuserMapper.selectList", 52);
 84         System.out.println("1---显示全部: " + sysuserList);
 85     }
 86 
 87     @Test
 88     public void test2_InsertUser() throws IOException {
 89         //5.执行SQL语句:定位待要执行的SQL语句
 90         Sysuser sysuser = new Sysuser();
 91         sysuser.setUname("小白");
 92         sysuser.setUpwd("123");
 93         int insert = sqlSession.insert("com.noma.mapper.SysuserMapper.insertUser", sysuser);
 94         Assert.assertEquals(1,insert);
 95         System.out.println("2---添加========");
 96     }
 97 
 98     @Test
 99     public void test3_UpdateUser() throws IOException {
100         //5.执行SQL语句:定位待要执行的SQL语句
101         Sysuser sysuser = new Sysuser();
102         sysuser.setUid(3);
103         sysuser.setUname("小黑");
104         sysuser.setUpwd("456");
105         int update = sqlSession.update("com.noma.mapper.SysuserMapper.updateUser", sysuser);
106         Assert.assertEquals(1,update);
107         System.out.println("3---修改========");
108     }
109 
110     @Test
111     public void test4_UserSelectOne() throws IOException {
112         //5.执行SQL语句:定位待要执行的SQL语句
113 //        Sysuser sysuser = sqlSession.selectOne("com.noma.mapper.SysuserMapper.findById",3);
114 //        System.out.println("4---52号: " + sysuser);
115 
116 //        // 一级缓存: 在web系统中,每次用户请求,后端开启sqlsession,查询完毕,session关闭.\
117 //        //session级别缓存(一级缓存):默认开启 同一个sqlSession
118 //        SysuserMapper sysuserMapper1 = sqlSession.getMapper(SysuserMapper.class);
119 //        Sysuser sysuser = sysuserMapper1.findById(1);
120 //        sqlSession.clearCache();                            //清理缓存
121 //        Sysuser sysuser1 = sysuserMapper1.findById(1);
122 //        System.out.println(sysuser);
123 
124         //二级缓存 : factory级别缓存(二级缓存):默认未开启. 同一个sqlSessionFactory
125         SqlSession sqlSession1 = sqlSessionFactory.openSession();
126         SysuserMapper sysuserMapper1 = sqlSession1.getMapper(SysuserMapper.class);
127         Sysuser sysuser1 = sysuserMapper1.findById(1);
128         sqlSession1.close();
129 
130         SqlSession sqlSession2 = sqlSessionFactory.openSession();
131         SysuserMapper sysuserMapper2 = sqlSession2.getMapper(SysuserMapper.class);
132         Sysuser sysuser2 = sysuserMapper2.findById(1);
133         sqlSession2.close();
134     }
135 
136     @Test
137     public void test5_DeleteUser() throws IOException {
138         int delete = sqlSession.delete("com.noma.mapper.SysuserMapper.deleteUser",69);
139         Assert.assertEquals(1,delete);
140         System.out.println("5---删除========");
141     }
142 
143     @Test
144     public void test6_AddUser() throws IOException {
145         //5.执行SQL语句:定位待要执行的SQL语句
146         Sysuser sysuser = new Sysuser();
147         sysuser.setUname("康娜");
148         sysuser.setUpwd("3445");
149         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
150         Integer addUser = sysuserMapper.addUser(sysuser);
151         long uid = sysuser.getUid();
152         System.out.println("6---自增ID========"+uid);
153     }
154 
155     @Test
156     public void test7_UserLikeUser() throws IOException {
157         //5.执行SQL语句:定位待要执行的SQL语句
158         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
159         List<Sysuser> sysuserList = sysuserMapper.findLikeUserName("三");
160         sysuserList.forEach(sysuser -> {
161             System.out.println(sysuser);
162         });
163     }
164 
165     @Test
166     public void test8_UserParams() throws IOException {
167         //5.执行SQL语句:定位待要执行的SQL语句
168         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
169         List<Sysuser> sysuserList = sysuserMapper.findByParams("三","2");
170         sysuserList.forEach(sysuser -> {
171             System.out.println(sysuser);
172         });
173     }
174 
175     @Test
176     public void test8_UserMap() throws IOException {
177         //5.执行SQL语句:定位待要执行的SQL语句
178         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
179         HashMap<String,String> map = new HashMap<>();
180         map.put("name","三");
181         map.put("upwd","3");
182         List<Sysuser> sysuserList = sysuserMapper.findByMap(map);
183         sysuserList.forEach(sysuser -> {
184             System.out.println(sysuser);
185         });
186     }
187 
188     @Test
189     public void test9_UserQueryEntity() throws IOException {
190         //5.执行SQL语句:定位待要执行的SQL语句
191         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
192         QueryEntity queryEntity = new QueryEntity();
193         queryEntity.setUname("三");
194         queryEntity.setPassword("2");
195         List<Sysuser> sysuserList = sysuserMapper.findByQueryEntity(queryEntity);
196         sysuserList.forEach(sysuser -> {
197             System.out.println(sysuser);
198         });
199     }
200 
201     @Test
202     public void test10_UserMapSorted() throws IOException {
203         //5.执行SQL语句:定位待要执行的SQL语句
204         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
205         HashMap<String,String> map = new HashMap<>();
206         map.put("sortedColumn","uid");
207         map.put("sorted","desc");
208         List<Sysuser> sysuserList = sysuserMapper.findBySorted(map);
209         sysuserList.forEach(sysuser -> {
210             System.out.println(sysuser);
211         });
212     }
213 
214     @Test
215     public void test11_UserContainRole() throws IOException {
216         //5.执行SQL语句:定位待要执行的SQL语句
217         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
218         Sysuser sysuser = sysuserMapper.findUserContainRoleByUid(2);
219         System.out.println("11==UserContainRole===>"+sysuser);
220     }
221 
222     @Test
223     public void test12_UsersByRid() throws IOException {
224         //5.执行SQL语句:定位待要执行的SQL语句
225         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
226         List<Sysuser> sysusers = sysuserMapper.findUsersByRid(1);
227         System.out.println("11==UserContainRole===>"+sysusers);
228     }
229 
230     @Test
231     public void test13_UsersDeleteByIdList() throws IOException {
232         //5.执行SQL语句:定位待要执行的SQL语句
233         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
234         ArrayList<Integer> idList = new ArrayList<>();
235         idList.add(67);
236         idList.add(66);
237         idList.add(68);
238         Integer integer = sysuserMapper.deleteUserByIdList(idList);
239     }
240 
241     @Test
242     public void test14_UsersDeleteByIds() throws IOException {
243         //5.执行SQL语句:定位待要执行的SQL语句
244         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
245         Integer[] ids = {64,65};
246         Integer integer = sysuserMapper.deleteUserByIds(ids);
247     }
248 
249     @Test
250     public void test14_UsersBatchtInsertUser() throws IOException {
251         //5.执行SQL语句:定位待要执行的SQL语句
252         SysuserMapper sysuserMapper = sqlSession.getMapper(SysuserMapper.class);
253         ArrayList<Sysuser> arrayList = new ArrayList<>();
254         Sysuser sysuser1 = new Sysuser("托尔","123");
255         Sysuser sysuser2 = new Sysuser("uzi","217");
256         Sysuser sysuser3 = new Sysuser("daggo","7777");
257         arrayList.add(sysuser1);
258         arrayList.add(sysuser2);
259         arrayList.add(sysuser3);
260         Integer integer = sysuserMapper.batchtInsertUser(arrayList);
261 
262     }
263 }
View Code

 

标签:02,SysuserMapper,文件,语句,sqlSession,sysuser,SQL,Mybatis,sysuserMapper
来源: https://www.cnblogs.com/noma/p/15914995.html