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. python elasticsearch 批量写入数据

    from elasticsearch import Elasticsearch from elasticsearch import helpers import pymysql import time ...

  2. 使用bind提供域名解析服务搭建

    正向解析实验 1.安装bind服务 2.在/etc目录中找到该服务程序的主配置文件,然后把第11行和第17行的地址均修改为any 3.正向解析参数如下: 4.编辑数据配置文件,从/var/named目 ...

  3. Nuget私有服务搭建实战

    最近更新了Nuget私有服务器的版本,之前是2.8.5,现在是2.11.3. Nuget服务器的搭建,这里有篇很详细的文章,跟着弄就好了: https://docs.microsoft.com/en- ...

  4. Javascript高级编程学习笔记(84)—— Canvas(1)基本用法

    Canvas绘图 Canvas自HTML5引入后,由于其炫酷的效果成为HTML5新增功能中最受欢迎的部分 Canvas元素通过在页面中设定一个区域,然后就可以使用JS在其中绘制图形 <canva ...

  5. [Swift]LeetCode60. 第k个排列 | Permutation Sequence

    The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the ...

  6. [Swift]LeetCode766. 托普利茨矩阵 | Toeplitz Matrix

    A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given ...

  7. [Swift]LeetCode828. 独特字符串 | Unique Letter String

    A character is unique in string S if it occurs exactly once in it. For example, in string S = " ...

  8. [Swift]LeetCode878. 第 N 个神奇数字 | Nth Magical Number

    A positive integer is magical if it is divisible by either A or B. Return the N-th magical number.  ...

  9. [Swift]LeetCode941. 有效的山脉数组 | Valid Mountain Array

    Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A ...

  10. 专访 | 新浪架构师:0-5年Java工程师的职业规划如何做?

    经历了2018年末的阵痛,大家都积攒着一股暗劲蠢蠢欲动. 3月初即将迎来2019年互联网行业换工作的大潮,技术工程师的升级换位对于一家互联网公司来说无疑是命脉般的存在——技术强则公司强! 如何做一个抢 ...