mybatis sumelect sum可以处理吗

MyBatis之家
【1.】MyBatis之家出品另一个好用eclipse插件---快速打开网页在浏览器
在做项目的过程中,就会考虑如果能自己写一个到开发包的插件的话就可以
节省好多时间,所以特此上传.不需要在地址栏敲容易出错的工程名和网页,
支持jsp,html,php,项目非常的小,仅19Kb,
&下载后复制到plugins目录,如果有dropins目录则复制到dropins目录,重启
eclipse即可,测试myeclipse6.5,eclipse3.2,myeclipse8.5通过.安装后的图
目前支持firefox和ie,可以修改端口..
点上图的第二个图标,效果如下:
无需在地址栏敲内容也可以浏览网页,开发中不需要频繁输入内容了。
【2.】MyBatis插件IBator在线安装地址 [复制链接]
不带开发包版大小0.98M,地址:
带完整开发包版大小9M,地址 :
【3.】mybatis代码自动生成eclipse插件简介
IBator是一个生成mybatis代码的eclipse插件,有如下特点:
1. 全自动生成pojo,xml,dao
2. 支持xml和annotation方式映射
3. 能生成数据库所有表,或选择部分表,能根据表的关系自动选择表来生成pojo和映射文件和dao
4. 如果表和字段名是关键字,能生成进行处理
5. 如果pojo中属性名是关键字,也能自动处理
6. 如果数据库中字段名有注释,也能生成注释,且支持中文(格式为utf-
8), 可以控制是否生成注释。
7. 像hibernate一样,能生成表的关系映射(目前仅支持xml方式映射)
8. 支持联合主键
支持物理分页,包括sql2000(server2000),业界首创,已测试mysql,oracel,sql2000,sql2005,sql2008
10. 能自动获取刚才添加的自动增长主键值(mysql,sqlserver已测试通过)
11.支持缓存(ehcache),一键开关是否开启,且增删改已自动配置好刷新缓存
12.支持精简版本生成,只生成简单Pojo和XML,不生成Example
13.支持DAO,Example改名,支持pojo,xml包路径更改
14. 生成简单测试类
15. 全自动整合spring, 能自动在spring配置文件中配置好DAO,声明式事务
16. 生成MyBatis总的配置文件
17. 解决了dtd文件不上网报错问题
18. 支持国际化(目前支持中英文两种)
& 配置数据库连接
& 生成后效果
& 生成XML映射文件,支持Hibernate一样的关系
& 生成XML映射文件,支持Hibernate一样的关系
& 简单的业务层,多种数据库物理分页,整合spring后
& 生成Pojo(Model类,支持数据库中文注释,且成了表的关系 )
& MyBatis的配置文件,整合spring了
& DAO层,能生成中文注释,支持多种数据库物理分页
【4.】MyBatis代码生成插件离线下载安装
IBator代码生成插件简介:
(本人测试的eclipse最低版本3.3、eclipse3.7测试/myeclipse6.5,最高
myeclipse8.5,)插件安装分两步,一.下载, 二.安装
1种包括开发包(集成mybatis4,spring3,两者整合包mybatis-spring,缓存
开发包ehcache-core-2.4.4.jar和log4j,mysql的jdbc驱动5.16),大小9M
另1种不包括任何开发包,生成代码后,要自己添加,大小0.98M
eclipse安装目录下如果有dropins目录,把下载的jar文件复制过去,没
有复制到plugins目录,重启eclipse右击工程,即可看到
【5.】Mybatis使用配置文件信息连接数据库
连接数据库信息:
&package com.
&import java.io.IOE
&import java.io.R
&import org.apache.ibatis.io.R
org.apache.ibatis.session.SqlS
org.apache.ibatis.session.SqlSessionF
org.apache.ibatis.session.SqlSessionFactoryBuilder;
&public class DataBase {
&//session工厂
private static SqlSessionFactory sessionF
//读取配置文件信息
&&& Reader
reader = Resources.getResourceAsReader
("config.xml");//reader 类读取配置文件
sessionFactory = new SqlSessionFactoryBuilder().build
(reader,"oracle");//获取数据库 这里是oracle环境
&& } catch (IOException e)
e.printStackTrace();
&//取session
ThreadLocal&SqlSession&&
threadLocal = new
ThreadLocal&SqlSession&();
&public& static SqlSession
getSession(){
&& SqlSession session =
threadLocal.get();
&& if (session==null){
&&& session =
sessionFactory.openSession();
threadLocal.set(session);
&& &return
&?xml version="1.0" encoding="UTF-8"
&&!DOCTYPE configuration PUBLIC
"-//ibatis.apache.org//DTD Config
3.0//EN"""&
config.xml
下面是数据库运行环境的XML文件内容&&&&&&&&&&&&&&&&&&&
&&configuration&
&!-- 数据库的运行环境,开发或产品 --&
&environments
default="development"&
&!-- oracle环境 --&
&!-- 这里也可以配置别的数据库环境--&
&environment id="oracle"&
&&&&&&&&&&
&!-- 事务管理 --&
&&&&&&&&&&
&transactionManager
type="JDBC"&
&&&&&&&&&&
&/transactionManager&
&!-- 连接数据库(数据源),使用连接池POOLED,不使用UNPOOLED
&&&&&&&&&&
&dataSource type="UNPOOLED"&
&&&&&&&&&&&&&
&property name="username"
value="scott"/&
&&&&&&&&&&&&&
&property name="password"
value="tiger"/&
&&&&&&&&&&&&&
&property name="driver"
value="oracle.jdbc.driver.OracleDriver"/&
&&&&&&&&&&&&&
&property name="url"
value="jdbc:oracle:thin:@127.0.0.1:1521:ora92"/&
&&&&&&&&&&
&/dataSource&
&/environment&&
&/environments&
&& &!-- 要加载的映射文件
resource="com/pojo/Student.xml"/&&!--
这里映射配置sql语句的XML文件---&
&/mappers&
-------------------------------------------------------------------
-------------------------------------------------------------------
SQL语句配置编写:
&?xml version="1.0" encoding="UTF-8"
&&!DOCTYPE
&PUBLIC "-//ibatis.apache.org//DTD Mapper
namespace="com.dao.StuDAO"&
&!-- 物理分页 --&
&select id="fenye" parameterType="map"
resultType="com.pojo.Student"&
select sid,sname,sage from&&
(select s.*,rownum rs from student s where
rownum&=#{end} )&&
ss where& ss.rs&#{begin}
&!-- 求条数 --&
&select id="getSum"
resultType="int"&
select count(*) from Student
&!-- 模糊查询 --&
&select id="mohuQuery" resultType="com.pojo.Student"
parameterType="string"&
select sid,sname,sage from student where sname like
concat('%',concat(#{value},'%'))
&&/mapper&
-------------------------------------------------------------------
-------------------------------------------------------------------
DAO类中的一些方法:
public List fenye(int page, int size) {
&& SqlSession session =
DataBase.getSession();
&& Map map = new HashMap();
&& map.put("begin", (page - 1) *
&& map.put("end", page *
&& List list =
session.selectList("com.dao.StuDAO.fenye", map);
&//求总条数
public int getSum(){
&& SqlSession session =
DataBase.getSession();
Integer&&&
= (Integer) session.selectOne
("com.dao.StuDAO.getSum");
&//求总页数
public int getCount(int size){
&& int sum =getSum();
&& return sum%size==0 ? sum/size
: sum/size+1;
&//模糊查询
public List mohuQuery(String name){
&& SqlSession session =
DataBase.getSession();
&& List list =
session.selectList("com.dao.StuDAO.mohuQuery",name);
这些就是基本的配置编写,个人可以根据你需要的来些sql语句,按照上面的
方式。之后就可以些业务类调用dao里面的方法,去实现业务。当然也有更好
的使用mybatis的方法,我就不祥细解释了解了,新手的话还是按这样慢慢了
解就好了,我个人觉得mybatis 在JSP中使用还是蛮方便的,使代码的编写速
度大有提高。
【6.】Ibaits Demo
囊括了常用的增删改查、传入数组、list或者map集合,有兴趣可以参考。。
【7.】Ibaits内不能含有中文,如何解决中文编码问题?
整个项目是UTF-8编码,ibaits只支持GB2312时才存能存在中文。此时该如何
处理中文问题?
01.create table aa(aid number,aname varchar(20))
02.select& *
03.insert into aa values(1,'中国');
04.insert into aa values(2,'湖南');
05.insert into aa values(3,'湖北');
06.insert into aa values(2,'北京');
07.--新增一列
08.alter table aa& add statu number
假使SQL语句为:
select decode(t.statu,0,'正常',1,'锁定')
假使我页面是以下拉框呈现,呈现数据出问题,乱码了!
一、通过Java传值,传过来的指替换中文
二、把查询出来的结果集放在Java 内处理
三、ibatis内用cadata声明
【8.】Ibatis DAO 事务
Ibatis DAO
框架提供了事务管理模块。而这个事务管理可以应用到很多场合,包括JDBC、Hibernate、JTA、SQLMAP等。
下面以最简单的JDBC来分析一下其如何实现事务管理。
首先来看一段代码: public class OrderService {
& private DaoManager daoM
& private OrderDao orderD
& public OrderService() {
daoManager = DaoConfig.getDaoManager();
orderDao = (OrderDao) daoManager.getDao(OrderDao.class);
& public void method() {
orderDao.method1();&&
//第一个事务
daoManager.startTransaction(); //开始第二个事务
orderDao.method1();
orderDao.method2();
mitTransaction();//提交第二个事务
} finally {
daoManager.endTransaction();
在method()方法里有着两个事务,如果在方法里不显式的调用
daoManager.startTransaction(),则每个DAO的一次方法调用就是一个独立的事务。Ibatis
DAO事务,有两个核心接口DaoTransactionManager和DaoTransaction对应着不同的数据库持久层实现,两个接口分别对应着不同实现,查看ibatis代码,可以发现这些manager实现事务,就是调用事务源的事务
& JdbcDaoTransactionManager
&&public void
commitTransaction(DaoTransaction trans) {
((JdbcDaoTransaction) trans).commit();
& JdbcDaoTransaction
& public JdbcDaoTransaction(DataSource dataSource)
connection = dataSource.getConnection();
if (connection == null) {
throw new DaoException("Could not start
transaction.& &
Cause: The DataSource returned a null connection.");
if (connection.getAutoCommit()) {
connection.setAutoCommit(false);
if (connectionLog.isDebugEnabled()) {
connection = ConnectionLogProxy.newInstance(connection);
} catch (SQLException e) {
throw new DaoException("Error starting JDBC
transaction.& &
Cause: " + e);
&& public void commit() {
} finally {
connection.close();
} catch (SQLException e) {
throw new DaoException("Error committing JDBC
transaction.&
Cause: " + e);
那么DaoTransactionManager以什么依据处理事务呢?
DaoTransactionState看看DaoTransactionState的代码,非常简单,四个常
量来表示事务处于的不同的状态
&& public static final
DaoTransactionState ACTIVE =
DaoTransactionState();
&& public static final
DaoTransactionState INACTIVE = new &
DaoTransactionState();
&& public static final
DaoTransactionState COMMITTED = new &
DaoTransactionState();
&& public static final
DaoTransactionState ROLLEDBACK = new &
DaoTransactionState();
& 那么实际程序中是如何控制事务的呢
& 在第一段代码中,我们是这样取得DAO
&& orderDao = (OrderDao)
daoManager.getDao(OrderDao.class);
实际daoManager返回的并不是orderDao的具体实现类,它返回的DaoProxy
&& public Object invoke(Object
proxy, Method method, Object[] args)
throws Throwable {
Object result =
if (PASSTHROUGH_METHODS.contains(method.getName())) {
result = method.invoke(daoImpl.getDaoInstance(), args);
} catch (Throwable t) {
throw ClassInfo.unwrapThrowable(t);
StandardDaoManager daoManager = daoImpl.getDaoManager();
DaoContext context = daoImpl.getDaoContext();
if (daoManager.isExplicitTransaction()) {
&&&&&&&&&&
context.startTransaction();
&&&&&&&&&&
result = method.invoke(daoImpl.getDaoInstance(), args);
} catch (Throwable t) {
&&&&&&&&&&
throw ClassInfo.unwrapThrowable(t);
& } else {
&&&&&&&&&&
context.startTransaction();
&&&&&&&&&&
result = method.invoke(daoImpl.getDaoInstance(), args);
&&&&&&&&&&
mitTransaction();
} catch (Throwable t) {
&&&&&&&&&&
throw ClassInfo.unwrapThrowable(t);
} finally {
&&&&&&&&&&
context.endTransaction();
&看到这段代码就非常清楚了,每调用DAO的一次方法时,如果不显式的调用
daoManager.startTransaction(),就会成为单独的一个事务。再看看ibatis
为我们提供的摸板JdbcDaoTemplate
&protected Connection getConnection() {
DaoTransaction trans = daoManager.getTransaction(this);
if (!(trans instanceof ConnectionDaoTransaction)) {
throw new DaoException("The DAO manager of type " +
daoManager.getClass().getName() +" cannot supply a JDBC
Connection
for this template, and is therefore not" +"supported by
JdbcDaoTemplate.");
return ((ConnectionDaoTransaction) trans).getConnection();
Ibatis控制多个DAO的事务实际是让这些DAO共用了一个DaoTransaction(ThreadLocal),一个Connection
这里是一个事务源的情况,如果多个事务源之间要完成全局事务,还是老老实实用分布式事务管理服务吧!
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。mybatis调用存储过程 -
- ITeye技术网站
博客分类:
看了下mybatis源码,有调用存储过程的例子,整理下。
参数形式:
create procedure sptest.adder(in addend1 integer, in addend2 integer, out theSum integer)
begin atomic
set theSum = addend1 + addend2;
&parameterMap type="map" id="testParameterMap"&
&parameter property="addend1" jdbcType="INTEGER" mode="IN"/&
&parameter property="addend2" jdbcType="INTEGER" mode="IN"/&
&parameter property="sum" jdbcType="INTEGER" mode="OUT"/&
&/parameterMap&
&update id="adderWithParameterMap" parameterMap="testParameterMap" statementType="CALLABLE"&
{call sptest.adder(?, ?, ?)}
public void testAdderAsUpdateWithParameterMap() {
SqlSession sqlSession = sqlSessionFactory.openSession();
Map&String, Object& parms = new HashMap&String, Object&();
parms.put("addend1", 3);
parms.put("addend2", 4);
SPMapper spMapper = sqlSession.getMapper(SPMapper.class);
spMapper.adderWithParameterMap(parms);
assertEquals(7, parms.get("sum"));
parms = new HashMap&String, Object&();
parms.put("addend1", 2);
parms.put("addend2", 3);
spMapper.adderWithParameterMap(parms);
assertEquals(5, parms.get("sum"));
} finally {
sqlSession.close();
带输入输出参数的存储过程:
sql代码:
create procedure sptest.getnames(in lowestId int, out totalrows integer)
reads sql data
dynamic result sets 1
BEGIN ATOMIC
declare cur cursor for select * from sptest.names where id &= lowestId;
select count(*) into totalrows from sptest.names where id &= lowestId;
&select id="getNamesAndItems" statementType="CALLABLE"
&select id="getNames" parameterType="java.util.Map" statementType="CALLABLE"
resultMap="nameResult"&
{call sptest.getnames(
#{lowestId,jdbcType=INTEGER,mode=IN},
#{totalRows,jdbcType=INTEGER,mode=OUT})}
public void testCallWithResultSet2_a1() {
SqlSession sqlSession = sqlSessionFactory.openSession();
SPMapper spMapper = sqlSession.getMapper(SPMapper.class);
Map&String, Object& parms = new HashMap&String, Object&();
parms.put("lowestId", 1);
List&Name& names = spMapper.getNamesAnnotated(parms);
assertEquals(3, names.size());
assertEquals(3, parms.get("totalRows"));
} finally {
sqlSession.close();
返回多个结果集
sql代码:
create procedure sptest.getnamesanditems()
reads sql data
dynamic result sets 2
BEGIN ATOMIC
declare cur1 cursor for select * from sptest.
declare cur2 cursor for select * from sptest.
open cur1;
open cur2;
&resultMap type="org.apache.ibatis.submitted.sptests.Name" id="nameResult"&
&result column="ID" property="id"/&
&result column="FIRST_NAME" property="firstName"/&
&result column="LAST_NAME" property="lastName"/&
&/resultMap&
&resultMap type="org.apache.ibatis.submitted.sptests.Item" id="itemResult"&
&result column="ID" property="id"/&
&result column="ITEM" property="item"/&
&/resultMap&
&select id="getNamesAndItems" statementType="CALLABLE"
resultMap="nameResult,itemResult"&
{call sptest.getnamesanditems()}
public void testGetNamesAndItems() throws SQLException {
SqlSession sqlSession = sqlSessionFactory.openSession();
SPMapper spMapper = sqlSession.getMapper(SPMapper.class);
List&List&?&& results = spMapper.getNamesAndItems();
assertEquals(2, results.size());
assertEquals(4, results.get(0).size());
assertEquals(3, results.get(1).size());
} finally {
sqlSession.close();
上面就是几种常用的了。
1 sqlserver oracle sqlserver返回结果集是可以不要out参数的。如果sql中用的是select出结果,不需要配置out参数。多个结果集/结果集可以配置resultMap 来返回LIST,主要是调用selectList方法会自动把结果集加入到list中去的。
2 sql有返回值 用select标签
3 注意sql参数和mybatis参数的对应关系,这个这里就不讲了。
4 注意参数个数
我遇到的异常:
参数不匹配的原因,因为sqlserver 中我是直接返回select临时表结果,不需要配置存储过程输出参数。
list中的内容形式:
吐槽:
感觉网上的内容都一样,没有区别和针对性,还是要看看源码例子。
还有什么问题大家一起探讨啊。
时间晚了,明早还得上班,有些东西可能没说到,希望大家给点实际开发过程中的问题,给点意见。
浏览 60105
ddnzero 写道大哥能上个源码么? 上面的感觉不完全啊能上传个附件或发我邮箱么?
上面的是Mybatis官方测试的代码。你是用的什么数据库哦。试过了我是mysql 5.5 这个例子的存储过程有些问题,编译不过.换5.5的写法就好了.declare cur1 cursor for select * from sptest.& & declare cur2 cursor for select * from sptest.& & open cur1;& & open cur2;& 这个好像不行,直接select *就能返回结果集,还可以返回多个结果集.
大哥能上个源码么? 上面的感觉不完全啊能上传个附件或发我邮箱么?
上面的是Mybatis官方测试的代码。你是用的什么数据库哦。
这么简单的sql有必要搞存储过程吗,逻辑复杂点的sql,你用这种方式调用存储过程能行吗???这些都是官方的列子哦
浏览: 178446 次
能否给个例子 sqlserver的调不通啊
存储过程要占用数据库本身的计算资源,数据库本身增删改查已经够累 ...
&insert id=&insert ...
同原因 多谢87398人阅读
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:&
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.
下面我们通过代码实践:
采用Oracle的HR.Employees表
& & & & 实体:Employees
public class Employees {
&&& private Integer employeeId;
&&& private String firstN
&&& private String lastN
&&& private S
&&& private String phoneN
&&& private Date hireD
&&& private String jobId;
&&& private BigD
&&& private BigDecimal commissionP
&&& private Integer managerId;
&&& private Short departmentId;
&&& &!--List:forech中的collection属性类型是List,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 --&
&&& &select id=&getEmployeesListParams& resultType=&Employees&&
&&&&&&& select *
&&&&&&& from EMPLOYEES e
&&&&&&& where e.EMPLOYEE_ID in
&&&&&&& &foreach collection=&list& item=&employeeId& index=&index&
&&&&&&&&&&& open=&(& close=&)& separator=&,&&
&&&&&&&&&&& #{employeeId}
&&&&&&& &/foreach&
&&& &/select&
&&& &!--Array:forech中的collection属性类型是array,collection的值必须是:list,item的值可以随意,Dao接口中参数名字随意 --&
&&& &select id=&getEmployeesArrayParams& resultType=&Employees&&
&&&&&&& select *
&&&&&&& from EMPLOYEES e
&&&&&&& where e.EMPLOYEE_ID in
&&&&&&& &foreach collection=&array& item=&employeeId& index=&index&
&&&&&&&&&&& open=&(& close=&)& separator=&,&&
&&&&&&&&&&& #{employeeId}
&&&&&&& &/foreach&
&&& &/select&
&&& &!--Map:不单单forech中的collection属性是map.key,其它所有属性都是map.key,比如下面的departmentId --&
&&& &select id=&getEmployeesMapParams& resultType=&Employees&&
&&&&&&& select *
&&&&&&& from EMPLOYEES e
&&&&&&& &where&
&&&&&&&&&&& &if test=&departmentId!=null and departmentId!=''&&
&&&&&&&&&&&&&&& e.DEPARTMENT_ID=#{departmentId}
&&&&&&&&&&& &/if&
&&&&&&&&&&& &if test=&employeeIdsArray!=null and employeeIdsArray.length!=0&&
&&&&&&&&&&&&&&& AND e.EMPLOYEE_ID in
&&&&&&&&&&&&&&& &foreach collection=&employeeIdsArray& item=&employeeId&
&&&&&&&&&&&&&&&&&&& index=&index& open=&(& close=&)& separator=&,&&
&&&&&&&&&&&&&&&&&&& #{employeeId}
&&&&&&&&&&&&&&& &/foreach&
&&&&&&&&&&& &/if&
&&&&&&& &/where&
&&& &/select&
public interface EmployeesMapper {
&&& List&Employees& getEmployeesListParams(List&String& employeeIds);
&&& List&Employees& getEmployeesArrayParams(String[] employeeIds);
&&& List&Employees& getEmployeesMapParams(Map&String,Object& params);
测试方法(未贴完整代码):
&&& public void testGetEmployeesListParams() {
&&&&&&& List&String& employeeIds = Arrays.asList(&100&, &101&, &200&);
&&&&&&& List&Employees& result = employeesMapper
&&&&&&&&&&&&&&& .getEmployeesListParams(employeeIds);
&&&&&&& assertEquals(3, result.size());
&&& public void testGetEmployeesArrayParams() {
&&&&&&& String[] employeeIds = new String[] { &100&, &200& };
&&&&&&& List&Employees& result = employeesMapper
&&&&&&&&&&&&&&& .getEmployeesArrayParams(employeeIds);
&&&&&&& assertEquals(2, result.size());
&&& public void testGetEmployeesMapParams() {
&&&&&&& String departmentId = &60&;
&&&&&&& List&String& employeeIdsList = Arrays.asList(&103&, &104&, &105&);
&&&&&&& String[] employeeIdsArray = new String[] { &103&, &104& };
&&&&&&& // 传入多个参数
&&&&&&& Map&String, Object& params = new HashMap&String, Object&();
&&&&&&& params.put(&departmentId&, departmentId);
&&&&&&& params.put(&employeeIdsList&, employeeIdsList);
&&&&&&& params.put(&employeeIdsArray&, employeeIdsArray);
&&&&&&& List&Employees& result = employeesMapper.getEmployeesMapParams(params);
&&&&&&& assertEquals(3, result.size());
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:425746次
积分:2848
积分:2848
排名:第10817名
原创:29篇
转载:36篇
评论:45条
(1)(1)(1)(3)(5)(19)(1)(4)(6)(16)(4)(3)(7)(1)

我要回帖

更多关于 mybatis sum 的文章

 

随机推荐