MyBatis框架入门之(二)

在本篇文章中,没有对细节进行处理的很好,有很多晓得细节的遗漏,本文只是一个简单的快速的入门

MyBatis的快速入门

  1.导入MyBatis框架jar包
  2.配置文件
  3.SqlSessionFactoryBuilder,传入字节输入流,构建工厂
  4.SqlSessionFactory,创建SqlSession
  5.SqlSession执行selectList方法查询数据

Test类:

@Test
  public void myBatis_QuickStart() throws IOException {
    InputStream inputStream =
Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new
SqlSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory =
sqlSessionFactoryBuilder.build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    List<User> list = sqlSession.selectList("test.queryList");
    if(list!=null && list.size()>0){
      for(User user : list){
        System.out.println(user);
     }
   }
 }

sqlMapperConfig.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>
  <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/test?characterEncoding=utf8" />
        <property name="username" value="root" />
        <property name="password" value="root" />
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="UserMapper.xml" />
  </mappers>
</configuration>

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="test">
 <select id="queryList" resultType="com.itheima.pojo.User">
   select * from user
</select>
</mapper>

MyBatis的CRUD

这是目录结构

sqlMapperConfig.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>
<!--起别名-->
<typeAliases>
<package name="com.qingmu.domain"></package>
</typeAliases>
<!--配置数据源环境信息-->
<environments default="development">
<!--开发环境数据源配置-->
<environment id="development">
<!--
事务管理器
       type="JDBC" 当前MyBatis事务管理,使用的是JDBC的事务
       Connection接口方法 commit rollback
       type="MANAGERED" 不管理事务,交给其他框架管理
-->
<transactionManager type="JDBC"/>
<!--
数据源
        type="POOLED" 使用数据库连接池
        type="UNPOOLED" 不使用连接池
-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
<environment id="test">
<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/test?characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="UserMapper.xml"></mapper>
</mappers>
</configuration>

 domain包中的User类

package com.qingmu.domain;

/**
 * @Auther:qingmu
 * @Description:脚踏实地,只为出人头地
 * @Date:Created in 21:07 2019/3/30
 */
public class User {
    private Integer id;
    private String username;
    private String sex;
    private String birthday;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getDate() {
        return birthday;
    }

    public void setDate(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", date='" + birthday + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Usermapper

package com.qingmu.Mapper;

import com.qingmu.domain.User;

import java.util.List;

/**
 * @Auther:qingmu
 * @Description:脚踏实地,只为出人头地
 * @Date:Created in 21:15 2019/3/30
 */
public interface UserMapper {


    /**
     * 根据id删除一条数据
     */

    void deleteUser(Integer id);

    /**
     * 插入一条数据
     */
    void insertUser(User user);

    /**
     * 通过id查询用户
     * @param id
     * @return
     */
    User queryUserById(Integer id);


    /**
     * 根据用户名模糊查询
     */
    List<User> queryUserByLike();
}

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="test">
    <select id="queryUserById" resultType="com.qingmu.domain.User" parameterType="Integer">
select * from user where id = #{id}
    </select>

    <select id="queryUserByLike" resultType="com.qingmu.domain.User" parameterType="String">
        select * from user where username like #{username}
    </select>


    <!--
< selectKey>< /selectKey> 再执行一次SQL语句'
- 属性order:在insert之前或者之后执行
- keyProperty:查询的结果放在哪里显示
- resultType:查询结果的数据类型

注意:
主键自增:
1.selectKey会将得到的主键放入model的主键属性中
2.在使用主键自增的时候,不能对主键进行主动赋值,才能获取到这个主键.
3.使用user.getid()才能获取到这个返回来的那个值
主键非自增:
 <insert id="insert" parameterType="com.soft.mybatis.model.Customer">
         跟自增主键方式相比,这里的不同之处只有两点
                    1  insert语句需要写id字段了,并且 values里面也不能省略
                    2 selectKey 的order属性需要写成BEFORE 因为这样才能将生成的uuid主键放入到model中,
                    这样后面的insert的values里面的id才不会获取为空
              跟自增主键相比就这点区别,当然了这里的获取主键id的方式为 select uuid()
              当然也可以另写别生成函数。
    <selectKey keyProperty="id" order="BEFORE" resultType="String">
        select uuid()
    </selectKey>
    insert into t_customer (id,c_name,c_sex,c_ceroNo,c_ceroType,c_age)
    values (#{id},#{name},#{sex},#{ceroNo},#{ceroType},#{age})
</insert>

    -->
    <insert id="insertUser" parameterType="com.qingmu.domain.User">

        <selectKey order="AFTER" resultType="int" keyProperty="id">
            <!-- insert语句之后执行,查询结果集直接封装pojo对象-->
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into user values (#{id},#{username},#{sex},#{birthday},#{address})
    </insert>

    <!--根据id删除一条数据-->
    <delete id="deleteUser" parameterType="Integer" >
        DELETE  from user where id=#{id}
    </delete>


</mapper>

测试类:

package com.qingmu;

import com.qingmu.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
 * @Auther:qingmu
 * @Description:脚踏实地,只为出人头地
 * @Date:Created in 21:19 2019/3/30
 */
public class SqlMapperTest {

    private SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void before() {
        //       获取到工厂建造者对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//        通过本类加载器获取到一个流对象,这个流对象用来读取SqlMapperConfig.xml文件
        InputStream inputStream = SqlMapperTest.class.getClassLoader().getResourceAsStream("sqlMapperConfig.xml");
//        创建工厂对象
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }


    /**
     * 根据id删除一条数据
     */
    @Test
    public void deleteUser(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int delete = sqlSession.delete("test.deleteUser", 8);
        sqlSession.commit();
        System.out.println(delete);
    }



    /**
     * 插入一条数据
     */
    @Test
    public void insertTest() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
//        使用selectKey获取自增的主键,不能对主键进行设置
//        user.setId(8);
        user.setSex("男");
        user.setAddress("南京");
        user.setUsername("赵云");

        int insert = sqlSession.insert("test.insertUser", user);
//        不提交不能进入数据库
        sqlSession.commit();
        sqlSession.close();
//        将获取到的主键进行输出
        System.out.println(user.getId());
        System.out.println(insert);
    }


    /**
     * 查询一条数据  selectOne
     */
    @Test
    public void test() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = (User) sqlSession.selectOne("test.queryUserById", 2);
        System.out.println(user);
    }

    /**
     * 模糊查询  selectList
     */
    @Test
    public void listTest() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> user = sqlSession.selectList("test.queryUserByLike", "%王%");
        if (user != null && user.size() > 0) {
            for (User o : user) {
                System.out.println(o);
            }
        }
    }

}

本文中使用的数据库的结构为

在本文中,有使用selectKey标签,在新增一条数据以后,可以再将这条数据中的id取出来,以方便逻辑使用.

这个标签使用的时候,会将id封装在domian实体类中,然后使用getId(),将id获取出来.

posted @ 2019-03-31 11:17  King-DA  阅读(146)  评论(0编辑  收藏  举报