mybatis 2 -常用数据操作
1、写入数据并获取自增ID
XML配置:
<!-- 写入数据获取自增ID -->
<insert id="insertLog" parameterType="com.mamaguwen.entity.sys_loginlog" useGeneratedKeys="true" keyProperty="logid">
insert into sys_loginlog (UserName) values (#{username})
</insert>
测试代码:
@Test
public void insertLog() {
sys_loginlog model = new sys_loginlog();
model.setIslogin(true);
model.setLoginip("127.0.0.1");
model.setLogintime(new Date());
model.setUsername("rhythmk"); int total = loginlog.insertLog(model);
System.out.println("影响数据条:" + total);
System.out.println("ID:" + model.getLogid());
/*
* 影响数据条:1 ID:4
*/ }
2、更新数据
<!-- 更新数据 -->
<update id="updateLog" parameterType="com.mamaguwen.entity.sys_loginlog">
update sys_loginlog set username=#{username}
where LogId=#{logid}
</update>
/*
* 更新数据
*/
@Test
public void updateLog() {
sys_loginlog record = new sys_loginlog();
record.setLogid(4L);
record.setUsername("wangkun");
int total = loginlog.updateLog(record);
System.out.println("影响数据条:" + total);
}
3、返回单个字符串对象:
<!-- -返回单字段内容 -->
<select id="selectStringByKey" resultType="String" >
select UserName from sys_loginlog
where LogId = #{logid}
</select>
/*
* 返回当个简单对象
*/
@Test
public void selectStringByKey() {
String record = loginlog.selectStringByKey(4);
System.out.println("返回的字符串:" + record);
}
4、返回List对象
<select id="selectLogList" resultType="com.mamaguwen.entity.sys_loginlog">
select * from sys_loginlog
</select>
/*
* 获取所有用户日志
*/
@Test
public void selectLogList() {
List<sys_loginlog> list = loginlog.selectLogList();
for (sys_loginlog log : list) {
System.out.println(log.getUsername());
}
}
5、返回List<String> 对象
<select id="selectUserNameList" resultType="String">
select UserName from sys_loginlog
</select>
/*
* 获取所有用户名
*/
@Test
public void selectUserNameList() {
List<String> list = loginlog.selectUserNameList();
for (String str : list) {
System.out.println(str);
}
}
6、传入单个参数
<select id="selectLogByKey" resultType="com.mamaguwen.entity.sys_loginlog">
select * from sys_loginlog Where LogId=#{logid}
</select>
/*
* 根据主键获取日志
*/
@Test
public void selectLogByKey() {
sys_loginlog model = loginlog.selectLogByKey(5); String str = String.format("id:%d,username:%s", model.getLogid(),
model.getUsername());
System.out.println(str);
}
7、执行存储过程:
<!-- 执行存储过程 -->
<select id="callProc" resultType="String" >
<!--
drop procedure if exists ShowString;
CREATE PROCEDURE ShowString(
Str VARCHAR(30)
)
BEGIN
select Str as Item;
END;
CALL ShowString('rhythmk')
-->
call ShowString (#{str})
</select>
/*
* 执行存储过程
*/
@Test
public void callProc() {
String str = loginlog.callProc("rhytmk");
System.out.println(str);
}
8、批量写入数据
<!-- 批量执行SQL -->
<!-- 生成SQL:
insert into sys_loginlog (username) values ('a'),('b')
-->
<insert id="insertBatch">
insert into sys_loginlog (username) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.username})
</foreach>
</insert>
/*
* 批量写入
*/
@Test
public void insertBatch() {
List<sys_loginlog> list = new ArrayList<sys_loginlog>();
for (int i = 0, j = 10; i < j; i++) {
sys_loginlog log = new sys_loginlog();
log.setUsername(String.format("wangkun%s", i));
list.add(log);
}
int total = loginlog.insertBatch(list);
System.out.println("生成数据条:" + total);
}
9、将字符串当参数出入进去
<select id="selectLogByMap" parameterType="Map" resultType="com.mamaguwen.entity.sys_loginlog">
select * from sys_loginlog
where (username=#{username1} or username=#{username2} )
</select>
/*
* 通过Map传入参数
*/
@Test
public void selectLogByMap()
{
Map<String, String> map=new HashMap<String,String>();
map.put("username1", "rhythmk");
map.put("username2", "wangkun");
List<sys_loginlog> list= loginlog.selectLogByMap(map);
for(sys_loginlog model:list)
{
String info= String.format("id%d,username%s", model.getLogid(),
model.getUsername());
System.out.println(info);
}
}
10、#{}与${}的区别
假如数据库 sys_loginlog表中有username=a,b两条数据。此时按下面配置文件,我传入'a','b' 则无法获取数据。
<select id="selectLogByUserName" parameterType="Map" resultType="com.mamaguwen.entity.sys_loginlog">
select * from sys_loginlog
where username in ( #{username} )
</select>
现修改where条件,换成${},那么传入的参数讲直接体会SQL中对应的文本 :
select * from sys_loginlog
where username in ( ${username} )
通过执行上面语句 生成的SQL为 : select * from sys_loginlog where username in ('a','b')
备注:
表结构:
CREATE TABLE `sys_loginlog` (
`LogId` bigint(20) NOT NULL AUTO_INCREMENT,
`UserName` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`Pwd` varchar(32) COLLATE utf8_bin DEFAULT NULL,
`IsLogin` bit(1) DEFAULT NULL,
`LoginIp` varchar(64) COLLATE utf8_bin DEFAULT NULL,
`LoginTime` datetime DEFAULT NULL,
PRIMARY KEY (`LogId`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Mapp数据操作接口:
public interface sys_loginlogMapper { /*
* 写入日志并返回自增的ID
* */
int insertLog (sys_loginlog record); /* 更新数据
* */
int updateLog(sys_loginlog record); /*
* 返回当个简单对象
* */
String selectStringByKey(@Param("logid") int logId ); /*
* 获取所有用户日志
* */
List<sys_loginlog> selectLogList(); /*
* 获取所有用户名
* */
List<String> selectUserNameList(); /*
* 根据主键获取日志
* */
sys_loginlog selectLogByKey(@Param("logid") int logid); /*
* 执行存储过程
* */
String callProc(@Param("str") String str); /*
* 批量写入
* */
int insertBatch(List<sys_loginlog> list); /*
* 通过Map传入参数
* */
List<sys_loginlog> selectLogByMap(Map<String, String> map); }
测试用例代码:
package com.mamaguwen.dao.test; import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.management.loading.PrivateMLet; import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mamaguwen.dao.sys_loginlogMapper;
import com.mamaguwen.entity.sys_loginlog; @RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
"classpath:spring-mybatis.xml" })
public class TestSysloginlogMapper { private static final Logger logger = Logger.getLogger(Test_SysUser.class); private sys_loginlogMapper loginlog; public sys_loginlogMapper getLoginlog() {
return loginlog;
} @Autowired
public void setLoginlog(sys_loginlogMapper loginlog) {
this.loginlog = loginlog;
} /*
* 写入日志并返回自增的ID
*/
@Test
public void insertLog() {
sys_loginlog model = new sys_loginlog();
model.setIslogin(true);
model.setLoginip("127.0.0.1");
model.setLogintime(new Date());
model.setUsername("rhythmk"); int total = loginlog.insertLog(model);
System.out.println("影响数据条:" + total);
System.out.println("ID:" + model.getLogid());
/*
* 影响数据条:1 ID:4
*/ } /*
* 更新数据
*/
@Test
public void updateLog() {
sys_loginlog record = new sys_loginlog();
record.setLogid(4L);
record.setUsername("wangkun");
int total = loginlog.updateLog(record);
System.out.println("影响数据条:" + total);
} /*
* 返回当个简单对象
*/
@Test
public void selectStringByKey() {
String record = loginlog.selectStringByKey(4);
System.out.println("返回的字符串:" + record);
} /*
* 获取所有用户日志
*/
@Test
public void selectLogList() {
List<sys_loginlog> list = loginlog.selectLogList();
for (sys_loginlog log : list) {
System.out.println(log.getUsername());
}
} /*
* 获取所有用户名
*/
@Test
public void selectUserNameList() {
List<String> list = loginlog.selectUserNameList();
for (String str : list) {
System.out.println(str);
}
} /*
* 根据主键获取日志
*/
@Test
public void selectLogByKey() {
sys_loginlog model = loginlog.selectLogByKey(5); String str = String.format("id:%d,username:%s", model.getLogid(),
model.getUsername());
System.out.println(str);
} /*
* 执行存储过程
*/
@Test
public void callProc() {
String str = loginlog.callProc("rhytmk");
System.out.println(str);
} /*
* 批量写入
*/
@Test
public void insertBatch() {
List<sys_loginlog> list = new ArrayList<sys_loginlog>();
for (int i = 0, j = 10; i < j; i++) {
sys_loginlog log = new sys_loginlog();
log.setUsername(String.format("wangkun%s", i));
list.add(log);
}
int total = loginlog.insertBatch(list);
System.out.println("生成数据条:" + total);
} /*
* 通过Map传入参数
*/
@Test
public void selectLogByMap()
{
Map<String, String> map=new HashMap<String,String>();
map.put("username1", "rhythmk");
map.put("username2", "wangkun");
List<sys_loginlog> list= loginlog.selectLogByMap(map);
for(sys_loginlog model:list)
{
String info= String.format("id%d,username%s", model.getLogid(),
model.getUsername());
System.out.println(info);
}
}
}
mybatis 2 -常用数据操作的更多相关文章
- SNMP常用数据操作
SNMP常用数据操作 snmp编程中常见的数据类型基本上就是integer32/oct_str(字节数组)/counter64/timeticks/dateAndTime这些.很多其它的比如Truth ...
- SpringCloud或SpringBoot+Mybatis-Plus利用mybatis插件实现数据操作记录及更新对比
引文 本文主要介绍如何使用mybatis插件实现拦截数据库操作并根据不同需求进行数据对比分析,主要适用于系统中需要对数据操作进行记录.在更新数据时准确记录更新字段 核心:mybatis插件(拦截器). ...
- SpringCloud或SpringBoot+Mybatis-Plus利用AOP+mybatis插件实现数据操作记录及更新对比
引文 本文主要介绍如何使用Spring AOP + mybatis插件实现拦截数据库操作并根据不同需求进行数据对比分析,主要适用于系统中需要对数据操作进行记录.在更新数据时准确记录更新字段 核心:AO ...
- Android 常用数据操作封装类案例
1.DbHelper类 继承自SQLiteOpenHelper类,实现对数据库的基本操作 package com.example.utils; import android.content.Conte ...
- MySql常用数据操作
1.数据库操作: MySQL服务管理命令: 1.启动服务:sudo service mysql start 2.停止服务:sudo service mysql stop 3.重新启动服务:sudo s ...
- Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作
详细的Spring MVC框架搭配在这个连接中: Maven 工程下 Spring MVC 站点配置 (一) Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作 这篇主 ...
- Mybatis数据操作
Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作 详细的Spring MVC框架搭配在这个连接中: Maven 工程下 Spring MVC 站点配置 (一) M ...
- 在MyBatis中查询数据、涉及多参数的数据访问操作、插入数据时获取数据自增长的id、关联表查询操作、动态SQL、关于配置MyBatis映射没有代码提示的解决方案
1. 单元测试 在单元测试中,每个测试方法都需要执行相同的前置代码和后置代码,则可以自定义2个方法,分别在这2个方法中执行前置代码和后置代码,并为这2个方法添加@Before和@After注解,然后, ...
- 大数据(5) - HDFS中的常用API操作
一.安装java 二.IntelliJ IDEA(2018)安装和破解与初期配置 参考链接 1.进入官网下载IntelliJ IDEA https://www.jetbrains.com/idea/d ...
随机推荐
- 前端jsp页面script引入url项目名使用${appName}
<script src="/${appName}/commons/jslib/CommonValue.js"></script> 新建一个com.autum ...
- dbms_job.submit方式创建job,太老了
--方法一declarejobno number; begin dbms_job.submit(jobno, 'xxxx;', xxxx, 'xxxx'); commit ...
- The web application you are attempting to access on this web server is currently unavailable.......
今天去服务器安装了个.net 4.0 framework(原本有1.0和2.0的),配置好站点后,选择版本为4.0,访问出错,错误代码如下 Server Application Unavailable ...
- C#接口作用
1.C#接口的作用 : C#接口是一个让很多初学C#者容易迷糊的东西,用起来好像很简单,定义接口,里面包含方法,但没有方法具体实现的代码,然后在继承该接口的类里面要实现接口的所有方法的代码,但没有真正 ...
- 本地绑定域名及host做快速解析与域名屏蔽处理
在电脑中成功安装好IIS后,打开C:\WINDOWS\system32\drivers\etc\用记事本打开hosts文件,把127.0.0.1 localhost复制,粘贴到最后,然后把loca ...
- C++17中那些值得关注的特性(上)
C++17标准在2017上半年已经讨论确定,正在形成ISO标准文档,今年晚些时候会正式发布.本文将介绍最新标准中值得开发者关注的新特新和基本用法. 总的来说C++17相比C++11的新特性来说新特性不 ...
- guake terminal
类是gnome的终端,超级棒. F11可以全屏/半屏,F12可以显示/隐藏.右键--首选项可以设置配置信息.
- TypeScript学习笔记(七) - 命名空间
本篇将介绍TypeScript的命名空间,并简单说明一下与模块的区别. 在之前的例子里,有如下一段代码,通过修改这段代码来演示命名空间的用法. interface Animal { name: str ...
- 【转载】python安装numpy和pandas
转载:原文地址 http://www.cnblogs.com/lxmhhy/p/6029465.html 最近要对一系列数据做同比比较,需要用到numpy和pandas来计算,不过使用python安装 ...
- nexus bower 集成使用
创建nexus bower proxy host 比较简单,如下图: 安装bower && bower-nexus resolver npm install -g bower-nexu ...