Mybatis入门程序(二)

1、实现需求

添加用户

更新用户

删除用户

2、添加用户

  (1)映射文件User.xml(Mapper)中,配置添加用户的Statement

<!-- 添加用户:
    parameterType:指定输入参数类型是pojo(包括用户的信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值, mybatis通过 OGNL 获取对象的属性值-->
<insert id="insertUser" parameterType="com.bjxb.mybatis.pojo.User">
    insert into user(username, birthday, sex, address) value(#{username},#{birthday},#{sex},#{address})
</insert>

   

  (2)程序代码

// 添加用户信息
@Test
public void insertUserTest() {
    SqlSession sqlSession = null;

    try {
        // mybatis配置文件
        String resource = "config/SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 创建会话工厂,传入mybatis的配置文件信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 通过工厂的到SQLSession
        sqlSession = sqlSessionFactory.openSession();
        
        // 插入用户对象
        User user = new User();
        user.setUsername("zxy");
        user.setBirthday(new Date());
        user.setSex("0");
        user.setAddress("山西太原");
        sqlSession.insert("test.insertUser", user);
        
        // 提交事务
        sqlSession.commit();
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        // 释放资源
        sqlSession.close();
    }
}

3、自增主键返回

  mysql 自增主键,执行 insert 提交之前自动生成一个自增主键。

  通过 mysql 函数获取到刚插入记录的自增主键:LAST_INSERT_ID()

  是在 insert 之后调用

  修改 insertUser 定义:

<!-- 添加用户:
    parameterType:指定输入参数类型是pojo(包括用户的信息)
    #{}中指定pojo的属性名,接收到pojo对象的属性值, mybatis通过 OGNL 获取对象的属性值-->
<insert id="insertUser" parameterType="com.bjxb.mybatis.pojo.User">
    <!-- 
    将插入数据的主键返回,返回到user对象中
         SELECT LAST_INSERT_ID():得到刚insert进去的记录的主键值,只适用于自增主键
         keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性
         order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
      resultType:指定 SELECT LAST_INSERT_ID()的结果类型
--> <selectKey keyProperty="id" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> insert into user(id, username, birthday, sex, address) value(#{id},#{username},#{birthday},#{sex},#{address}) </insert>

4、非自增主键返回(使用UUID())

  使用 mysql 的 uuid()函数生成主键,需要修改表中 id 的字段为 string,长度设置成 35 位

  修改 insertUser 定义:

<insert id="insertUser" parameterType="com.bjxb.mybatis.pojo.User">
    <!-- 
        使用mysql的 uuid()生成主键
        执行过程:
        首先通过UUID(),将主键设置到user对象的id属性中
        其次在inset执行时,从user对象中,取出id属性值
-->
    <selectKey keyProperty="id"order="BEFORE" resultType="java.lang.String">
        SELECT UUID()
    </selectKey>
    insert into user(id, username, birthday, sex, address) value(#{id}, #{username},#{birthday},#{sex},#{address})
</insert>

5、通过 oracle 的序列生成主键:

<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
    SELECT 序列名.nextval()
</selectKey>
insert into user(id, username, birthday, sex, address) value(#{id}, #{username},#{birthday},#{sex},#{address})

6、删除用户

  (1)映射文件

<!-- 删除用户
         根据id删除用户,需要输入id值
 -->
<delete id="deleteUser" parameterType="java.lang.Integer">
    delete from user where id = #{id}
</delete>

   

  (2)代码

// 根据id删除用户信息
@Test
public void deleteUserTest() {
    SqlSession sqlSession = null;

    try {
        // mybatis配置文件
        String resource = "config/SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 创建会话工厂,传入mybatis的配置文件信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 通过工厂的到SQLSession
        sqlSession = sqlSessionFactory.openSession();

        // 传入id删除用户
        sqlSession.delete("test.deleteUser", 10);    
        
        // 提交事务
        sqlSession.commit();
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        // 关闭会话,释放资源
        sqlSession.close();
    }
}

 

7、更新用户

  (1)映射文件

<!-- 更新用户
        分析:
        需要传入用户的id
        需要传入用户的更新信息
        parameterType指定user对象,包括id和更新信息,注意: id必须存在
        #{id}: 从输入user对象中获取id属性值
 -->
<update id="updateUser" parameterType="com.bjxb.mybatis.pojo.User">
    update user set username=#{username}, birthday=#{birthday}, sex=#{sex}, address=#{address} where id = #{id}
</update>

  (2)代码

// 更新用户信息
@Test
public void updateUserTest() {
    SqlSession sqlSession = null;

    try {
        // mybatis配置文件
        String resource = "config/SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 创建会话工厂,传入mybatis的配置文件信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 通过工厂的到SQLSession
        sqlSession = sqlSessionFactory.openSession();
        
        // 更新用户信息
        User user = new User();
        // 必须设置id
        user.setId(11);
        user.setUsername("xy");
        user.setBirthday(new Date());
        user.setSex("0");
        user.setAddress("山西运城");
        sqlSession.insert("test.updateUser", user);
        
        // 提交事务
        sqlSession.commit();
    } catch (Exception e) {
        // TODO: handle exception
    } finally {
        // 释放资源
        sqlSession.close();
    }
}
原文地址:https://www.cnblogs.com/xb1223/p/10197060.html