MyBatis 学习 - 注解
首先,POJO
/**
* @Title: Question.java
* @Package com.test.model
* @Description: TODO(POJO Question)
* Copyright: Copyright (c) 2012 Company China Foreign Exchange Trade System and National Interbank Funding Center.
* Building 24,1387 ZhangDong Road, Shanghai, China.
* All Rights Reserved.
* Company: Insigma HT
* @author Ares
* @date 2013-06-24 下午3:48:31
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2013-06-24 Ares initial
*/
package com.test.model; import java.util.Date; /**
*
* @author Ares
* @Describe TODO(POJO Question)
*
*/
public class Question { private String id;
private int qorder;
private String qname;
private String qcontent;
private Date updateTime; public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getQorder() {
return qorder;
}
public void setQorder(int qorder) {
this.qorder = qorder;
}
public String getQname() {
return qname;
}
public void setQname(String qname) {
this.qname = qname;
}
public String getQcontent() {
return qcontent;
}
public void setQcontent(String qcontent) {
this.qcontent = qcontent;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
} }
继续,Mapper
/**
* @Title: QuestionDAO.java
* @Package com.test.dao
* @Description: TODO(Question Mapper)
* Copyright: Copyright (c) 2012 Company China Foreign Exchange Trade System and National Interbank Funding Center.
* Building 24,1387 ZhangDong Road, Shanghai, China.
* All Rights Reserved.
* Company: Insigma HT
* @author Ares
* @date 2013-06-24 下午3:48:31
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2013-06-24 Ares initial
*/
package com.test.dao; import java.util.List; import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import com.test.model.Question; /**
*
* @author Ares
* @Describe TODO(Question Mapper)
*
*/
public interface QuestionDAO { /**
* AddBy Ares
* TODO(find all questions)
*/
@Select("SELECT * FROM Question")
public List<Question> findAll(); /**
* AddBy Ares
* TODO(find question by ID)
*/
@Select("SELECT * FROM Question WHERE ID = #{id}")
public Question findByID(@Param("id")String id); /**
* AddBy Ares
* TODO(just save one question)
*/
@Insert("INSERT INTO Question VALUES(#{id},#{qorder},#{qname},#{qcontent},#{updateTime})")
public void save(Question question); /**
* AddBy Ares
* TODO(save all questions in list)
*/
@InsertProvider(type=SqlProvider.class, method="saveAll")
public void saveAll(List<Question> list); }
上面的Mapper中,saveAll方法使用了SqlProvider,这个是用作批量添加使用的。
/**
* @Title: SqlProvider.java
* @Package com.test.dao
* @Description: TODO(SqlProvider)
* Copyright: Copyright (c) 2012 Company China Foreign Exchange Trade System and National Interbank Funding Center.
* Building 24,1387 ZhangDong Road, Shanghai, China.
* All Rights Reserved.
* Company: Insigma HT
* @author Ares
* @date 2013-6-24 下午3:48:31
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2013-6-24 Ares initial
*/
package com.test.dao; import java.text.MessageFormat;
import java.util.List;
import java.util.Map; import com.test.model.Question; /**
* @author Ares
* TODO(SqlProvider)
*/
public class SqlProvider { private static final String TABLE = "question"; public String saveAll(Map<String, List<Question>> params){
List<Question> list = (List<Question>)params.get("list");
if(list!=null){
StringBuffer sb = new StringBuffer("insert into ").append(TABLE).append(" values ");
MessageFormat mf = new MessageFormat("(#'{'list[{0}].id}, #'{'list[{0}].qorder}, #'{'list[{0}].qname}, #'{'list[{0}].qcontent}, #'{'list[{0}].updateTime})");
for (int i=0; i<list.size(); i++) {
sb.append(mf.format(new Object[]{i}));
if (i < list.size() - 1) {
sb.append(",");
}
}
System.out.println(sb.toString());
return sb.toString();
}
return null;
} }
接下来,把配置文件拿过来,
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"mybatis-3-config.dtd"> <configuration> <typeAliases>
<package name="com.test.model"/>
</typeAliases> <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://localhost:3306/test?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="test"/>
</dataSource>
</environment>
</environments> <mappers>
<package name="com.test.dao"/>
</mappers>
<!--
<mappers>
<mapper resource="com/test/model/Question.xml"/>
</mappers>
-->
</configuration>
最后,开始测试
/**
* @Title: MyBatisTest.java
* @Package com.test.test
* @Description: TODO(MyBatisTest)
* Copyright: Copyright (c) 2012 Company China Foreign Exchange Trade System and National Interbank Funding Center.
* Building 24,1387 ZhangDong Road, Shanghai, China.
* All Rights Reserved.
* Company: Insigma HT
* @author Ares
* @date 2013-06-24 下午3:48:31
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2013-06-24 Ares initial
*/
package com.test.test; import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test; import com.test.dao.QuestionDAO;
import com.test.model.Question; /**
* @author Ares
* TODO(MyBatisTest)
*/
public class MyBatisTest { @Test
public void testMyBatis(){
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(this.getClass().getResourceAsStream("/com/test/cfg/sqlMapClient.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
QuestionDAO questionDao = sqlSession.getMapper(QuestionDAO.class); List<Question> list = new ArrayList<Question>();
Question q = new Question();
q.setId(UUID.randomUUID().toString());
q.setQname("Are you ok?");
q.setQcontent("I'm ok.");
q.setQorder(6);
q.setUpdateTime(new Date());
list.add(q); Question q2 = new Question();
q2.setId(UUID.randomUUID().toString());
q2.setQname("How are you?");
q2.setQcontent("I'm ok.");
q2.setQorder(6);
q2.setUpdateTime(new Date());
list.add(q2); questionDao.saveAll(list);
sqlSession.commit(); List<Question> questions = questionDao.findAll();
for (Question question : questions) {
System.out.println(question.getQname() + " \tReply: "+question.getQcontent());
} sqlSession.close();
}
}
MyBatis 学习 - 注解的更多相关文章
- mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现
项目结构 基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程) 开始体验 1.新建项目,新建类MybatisUtil.java,路径:src/util/Mybatis ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合(转载)
孤傲苍狼 只为成功找方法,不为失败找借口! MyBatis学习总结(八)--Mybatis3.x与Spring4.x整合 一.搭建开发环境 1.1.使用Maven创建Web项目 执行如下命令: m ...
- (原创)mybatis学习一,夯实基础
一,what?(是什么) MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBatis可 ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- 【Todo】Mybatis学习-偏理论
之前写过好几篇Mybatis相关的文章: http://www.cnblogs.com/charlesblc/p/5906431.html <SSM(SpringMVC+Spring+Myba ...
- MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存
目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...
- MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql
目录(?)[-] 一MyBatis简介与配置MyBatisSpringMySql MyBatis简介 MyBatisSpringMySql简单配置 搭建Spring环境 建立MySql数据库 搭建My ...
随机推荐
- vue组件调用(用npm安装)
vue用webpack打包方式新建项目,注意刚开始可以先关闭路由和代码错误检测功能 1.建立了一个Hi.vue的组件 <template> <div>Hi~~{{msg}}-- ...
- [转]sql:除非另外还指定了 TOP 或 FOR XML,否则,ORDER BY 子句在视图、内联函数、派生表、子查询
执行sql语句: select * from ( select * from tab where ID>20 order by userID desc ) as a order by date ...
- JavaScript:Object.prototype.toString进行数据类型判定
在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. var arr = []; console.log(Obje ...
- MySql图解给表添加外键
关于外键约束的几种方式,请移步鄙人的另外一个博客中的博文 http://blog.csdn.net/hadues/article/details/52558184
- 好工具 VHD
通过powershell 互转 Convert-VHD –Path F:\debian.vhdx –DestinationPath F:\debian.vhd 举个栗子 附加参考 Convert-VH ...
- Oracle:shared memory realm does not exist
1. 先描述一个连接Oracle 10g的错误:“shared memory realm does not exist” 如图所示Sqlplus连接时出现这个错误: 2. Oracle 服务器主要组件 ...
- na+mb与gcd
蒜头君和花椰妹在玩一个游戏,他们在地上将 nn 颗石子排成一排,编号为 11 到 nn.开始时,蒜头君随机取出了 22 颗石子扔掉,假设蒜头君取出的 22 颗石子的编号为 aa, bb.游戏规则如下, ...
- 对java中arraylist深入理解
1.ArrayList插入删除一定慢么? 取决于你删除的元素离数组末端有多远,ArrayList拿来作为堆栈来用还是挺合适的,push和pop操作完全不涉及数据移动操作. 2.ArrayList的遍历 ...
- pictureBox
private void pictureBox1_Click(object sender, EventArgs e) { openFileDialog1.Filter="*.jpg|*.jp ...
- STM32CubeMX使用方法及功能介绍
推荐 分享一个朋友的人工智能教程,零基础!通俗易懂!希望你也加入到人工智能的队伍中来! http://www.captainbed.net/strongerhuang Ⅰ.写在前面 学习本文之前可以查 ...