Mybatis入门之增删改查

Mybatis如果操作成功,但是数据库没有更新那就是得添加事务了。(增删改都要添加)-----

浪费了我40多分钟怀疑人生后来去百度。。。

导入包:

引入配置文件:

sqlMapConfig.xml(mybatis的核心配置文件)、log4j.properties(日志记录文件)

<?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整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <!-- 加载映射文件 -->
<mappers>
<mapper resource="deep/sqlmap/Account.xml"/>
</mappers>
</configuration>
#Global logging configuration
log4j.rootLogger=DEBUG,stdout
#Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n

数据库准备:(略)

实体类编写后针对实体类编写的映射文件

<?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"> <!-- namespace:命名空间,用于隔离sql -->
<mapper namespace="account">
<!-- 通过ID查询一个用户 -->
<!-- parameterType入参的类型,resultType返回值的类型 -->
<!-- #{v} 参数占位符 -->
<select id="findUserById" parameterType="Integer" resultType="deep.pojo.Account">
select * from account where id = #{v}
</select> <!--
#{} 占位符
${} 字符串拼接
-->
<!-- 根据用户名模糊查询用户列表 -->
<select id="findUserByUsername" parameterType="String" resultType="deep.pojo.Account">
<!-- 这种方式不防止sql注入 -->
<!-- select * from account where username like '%${value}%' -->
select * from account where username like "%"#{v}"%"
</select> <!-- 添加用户 -->
<insert id="insertUser" parameterType="deep.pojo.Account">
<!-- 在查询结束后查询最新插入的id,并返回给对象,赋值给对象的id属性 -->
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into account (username,birthday,address,sex)
value (#{username},#{birthday},#{address},#{sex})
</insert> <!-- 更新 -->
<update id="updateUserById" parameterType="deep.pojo.Account">
update account
set username = #{username},sex = #{sex},birthday = #{birthday},address = #{address}
where id = #{id}
</update> <!-- 删除 -->
<delete id="deleteUserById" parameterType="Integer">
delete from account
where id = #{v}
</delete> </mapper>

执行

package deep.junit;

import java.io.InputStream;
import java.util.Date;
import java.util.List; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test; import deep.pojo.Account; public class MyBatisFirstTest { @Test
public void testMybatis() throws Exception {
//加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
//创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(); //执行sql语句
Account account = sqlSession.selectOne("account.findUserById", 1); System.out.println(account);
} //根据用户名称模糊查询用户列表
@Test
public void testFindUserByUsername() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource); //创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(); //执行sql语句
List<Account> accounts = sqlSession.selectList("account.findUserByUsername", "五");
for (Account account : accounts) {
System.out.println(account);
}
} //根据用户名称模糊查询用户列表
@Test
public void testInsertUser() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource); //创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(); //执行sql语句
Account account = new Account();
account.setUsername("麻子2");
account.setBirthday(new Date());
account.setAddress("sdfasdfads");
account.setSex("男");
int i = sqlSession.insert("account.insertUser", account); //自己手动提交事务
sqlSession.commit(); System.out.println(account.getId());
} //更新用户
@Test
public void testUpdateUserById() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource); //创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(); //执行sql语句
Account account = new Account();
account.setId(28);
account.setUsername("麻子更新");
account.setBirthday(new Date());
account.setAddress("地址更新");
account.setSex("女");
int update = sqlSession.update("account.updateUserById", account); //自己手动提交事务
sqlSession.commit();
} //更新用户
@Test
public void testDelete() throws Exception{
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource); //创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); //创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.delete("account.deleteUserById", 28); //自己手动提交事务
sqlSession.commit();
} }

Mybatis入门之增删改查的更多相关文章

  1. MyBatis入门2_增删改查+数据库字段和实体字段不一致情况

    本文为博主辛苦总结,希望自己以后返回来看的时候理解更深刻,也希望可以起到帮助初学者的作用. 转载请注明 出自 : luogg的博客园 谢谢配合! 当数据库字段和实体bean中属性不一致时 之前数据库P ...

  2. MyBatis入门案例 增删改查

    一.MyBatis入门案例: ①:引入jar包 ②:创建实体类 Dept,并进行封装 ③ 在Src下创建大配置mybatis-config.xml <?xml version="1.0 ...

  3. mybatis入门(二):增删改查

    mybatis的原理: 1.mybatis是一个持久层框架,是apache下的顶级项目 mybatis托管到googlecode下,目前托管到了github下面 2.mybatis可以将向prepar ...

  4. mybatis入门二-----增删改查

    一.使用MyBatis对表执行CRUD操作——基于XML的实现 1.定义sql映射xml文件 userMapper.xml文件的内容如下: <?xml version="1.0&quo ...

  5. MyBatis简单的增删改查以及简单的分页查询实现

    MyBatis简单的增删改查以及简单的分页查询实现 <? xml version="1.0" encoding="UTF-8"? > <!DO ...

  6. MyBatis -- 对表进行增删改查(基于注解的实现)

    1.MyBatis对数据库表进行增/删/改/查 前一篇使用基于XML的方式实现对数据库的增/删/改/查 以下我们来看怎么使用注解的方式实现对数据库表的增/删/改/查 1.1  首先须要定义映射sql的 ...

  7. Spring Boot 使用Mybatis注解开发增删改查

    使用逆向工程是遇到的错误 错误描述 org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): c ...

  8. Mybatis实现简单增删改查

    Mybatis的简单应用 学习内容: 需求 环境准备 代码 总结: 学习内容: 需求 使用Mybatis实现简单增删改查(以下是在IDEA中实现的,其他开发工具中,代码一样) jar 包下载:http ...

  9. SpringMVC,MyBatis商品的增删改查

    一.需求 商品的增删改查 二.工程结构 三.代码 1.Mapper层 (1) ItemsMapperCustom.java package com.tony.ssm.mapper; import ja ...

随机推荐

  1. windows10下Kafka环境搭建

    内容小白,包含JDK+Zookeeper+Kafka三部分.JDK:1)   安装包:Java SE Development Kit 9.0.1      下载地址:http://www.oracle ...

  2. Android找回密码功能 手机找回、邮箱找回

    找回密码功能设计:https://blog.csdn.net/qq_33472765/article/details/82287404?utm_source=blogxgwz0 手机找回:https: ...

  3. TCPDF 背景图片透明度

    1.TCPDF 背景图片透明度  参考:https://bbs.csdn.net/topics/392364981 效果: 2.画一条线: 2.1方法解说  /*画一条线: x1:线条起点x坐标 y1 ...

  4. 发现了学校教务处官网的两个BUG

    许久没有写博客了,感觉自己技术还差的好多-_-好像没啥好写的,之前学完了某易的WEB安全基础视频教程,自认对WEB安全入了门,忍不住就想拿学校教务处官网来练练手 教务处登录界面如图所示(为保护隐私,部 ...

  5. [.net 面向对象程序设计深入](18)实战设计模式——设计模式使用场景及原则

    [.net 面向对象程序设计深入](18)实战设计模式——设计模式使用场景及原则 1,什么是设计模式? 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计 ...

  6. Dubbo 分布式事务一致性实现

    我觉得事务的管理不应该属于Dubbo框架, Dubbo只需实现可被事务管理即可, 像JDBC和JMS都是可被事务管理的分布式资源, Dubbo只要实现相同的可被事务管理的行为,比如可以回滚, 其它事务 ...

  7. ansible基础-Jinja2模版 | 测试

    一 简介 注:本文demo使用ansible2.7稳定版 Jinja2的测试语句被用来评估一个条件表达式,并且最终返回True或False,经常和「when」语句搭配使用. 测试语句和过滤器的相同点: ...

  8. [Swift]LeetCode143. 重排链表 | Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You may not mod ...

  9. [Swift]LeetCode350. 两个数组的交集 II | Intersection of Two Arrays II

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  10. [Swift]LeetCode417. 太平洋大西洋水流问题 | Pacific Atlantic Water Flow

    Given an m x n matrix of non-negative integers representing the height of each unit cell in a contin ...