iBates学习(2014年6月25日)

在网上看到有些公司职位要求里有熟悉iBatis,现在iBatis改名为myBatis。今天利用午休时间在网上查了些资料,了解了一下iBatis。明天待续

导入jar包,写好属性文件、配置文件就可以了。只是实体类的@Override public String toString()这个方法是何意,必须重写吗,为什么要重写这个? iBatis官网为:http://www.mybatis.org/

熟悉Hibernate(实现了POJO 和数据库表之间的映射,以及SQL 的自动生成和执行)的人学iBatis非常简单,目前主流的ORM ,例如Hibernate,都对数据库结构提供了较为完整的封装,提供了从POJO 到数据库表的全套映射机制。程序员往往只需定义好了POJO 到数据库表的映射关系,即可通过Hibernate提供的方法完成持久层操作。程序员甚至不需要对SQL 的熟练掌握, Hibernate会根据制定的存储逻辑,自动生成对应的SQL 并调用JDBC 接口加以执行。有人讲iBatis是半自动化的(相对于Hibernate来讲),iBatis不会自动生成SQL语句,iBatis关注与POJO与SQL之间的映射。具体的SQL 需要程序员编写,然后通过映射配置文件,将SQL 所需的参数,以及返回的结果字段映射到指定POJO 。

既然有像Hibernate这样全自动化的ORM Mapping,那么怎样的情况下更适合使用iBatis呢?在网上查了一下前辈的总结,下面列一下以供参考。

1. 系统的部分或全部数据来自现有数据库,处于安全考虑,只对开发团队提供几条Select SQL(或存储过程)以获取所需数据,具体的表结构不予公开。
2. 开发规范中要求, 所有牵涉到业务逻辑部分的数据库操作,必须在数据库层由存储过程实现(就金融行业而言,工商银行、中国银行、交通银行,都在开发规范中严格指定)

3. 系统数据处理量巨大,性能要求极为苛刻,这往往意味着我们必须通过经过高度优化的SQL 语句(或存储过程)才能达到系统性能设计指标。

iBatis通过映射文件配置SQL,使得对数据库的操作更加的灵活(Hibernate也应该是有对SQL的优化的)。

明天写一个小程序试试看。代码待续……


SpringMVC + MyBatis + MySQL 

Spring 配置文件

<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans  
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
      http://www.springframework.org/schema/context  
      http://www.springframework.org/schema/context/spring-context.xsd  
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/mvc  
      http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
      
     <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->  
     <mvc:annotation-driven />  
     <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->  
     <context:component-scan base-package="com.longriver.netpro" />
     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/pages/" p:suffix=".jsp" />

<!-- 使用annotation自动注册bean,并保证@Required,@Autowired的属性被注入 -->
    <context:annotation-config />
<context:component-scan base-package="com.longriver.netpro" />

<!-- 读取数据源配置文件 -->
<bean id="dataSoucresConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:config/properties/jdbc.properties" />
</bean>

<bean id="basicDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
  <property name="driverClass" value="${jdbc.driverClass}" />
  <property name="idleConnectionTestPeriodInMinutes" value="${jdbc.idleConnectionTestPeriodInMinutes}" />
  <property name="idleMaxAgeInMinutes" value="${jdbc.idleMaxAgeInMinutes}" />
  <property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}" />
  <property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}" />
  <property name="partitionCount" value="${jdbc.partitionCount}" />
  <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
  <property name="statementsCacheSize" value="${jdbc.statementsCacheSize}" />
  <property name="logStatementsEnabled" value="${jdbc.logStatementsEnabled}" />
</bean>
<!-- local本地 DBSource -->
<bean id="dataSource" parent="basicDataSource">
<property name="jdbcUrl" value="${jdbc.url.jdbcUrl}" />
  <property name="username" value="${jdbc.username}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>


<!-- MyBatis SQLSessionFactory 配置MyBatis XML文件所在位置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:config/mybatis/Configuration.xml" />
<property name="mapperLocations">
<list>
<value>classpath*:config/mybatis/sqlMapper/*.xml</value>
</list>
</property>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

</beans>  


MyBatis  XML文件:写SQL语句的文件。XML的写法可以参照DTD文件  

<?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">
<mapper namespace="corpusMapper">
<select id="list" parameterType="map" resultType="corpus"> <!-- 返回值保存在名为corpus的对象中 -->
SELECT * FROM corpus_temp WHERE 1 = 1
<if test="siteUrl != null and siteUrl != ''">
AND site_url = #{siteUrl}
</if>
</select>
<mapper/>

对象配置

<?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>
<typeAliases>

<typeAlias alias="corpus" type="com.longriver.netpro.corpus.entity.Corpus"/>
</typeAliases>
</configuration>



数据库基本操作接口的实现


package com.longriver.netpro.basic.impl;


import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


import com.longriver.netpro.basic.IBasicDaoSupport;


/**
 * 主要的 dao 类
 * @author Administrator
 *
 */


@Repository("basicDaoSupport")
public class BasicDaoSupportImpl extends SqlSessionDaoSupport implements IBasicDaoSupport {


/**
* mybatis-spring-1.2.x.jar 版本的 sqlSessionTemplate 注入有所改动,必须重写次方法
*/
@Autowired
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
super.setSqlSessionTemplate(sqlSessionTemplate);
}

@Override
public Object delete(String sql, Object obj) throws Exception {
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.delete(sql, obj);
} catch (Exception e) {
throw e;
}
return object;
}


@Override
public Object deleteBatch(String sql, Object[] obj) throws Exception {
// TODO Auto-generated method stub
return null;
}


@Override
public Object deleteBatch(String sql, List<?> list) throws Exception {
int count = 0;
@SuppressWarnings("unused")
SqlSession session = null;
try {
session = this.getSqlSession();
for(Object entity : list) {
count += session.delete(sql, entity);
}
} catch (Exception e) {
e.printStackTrace();
count = -1;
}
return count;
}


@Override
public Object findForList(String sql, Object obj) throws Exception {
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.selectList(sql, obj);
} catch (Exception e) {
throw e;
}
return object;
}


@Override
public Object findForList(String sql) throws Exception {
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.selectList(sql);
} catch (Exception e) {
throw e;
}
return object;
}


@Override
public Object findForMap(String sql, Object obj, String key, String value)
throws Exception {
// TODO Auto-generated method stub
return null;
}


@Override
public Object findForObject(String sql, Object obj) throws Exception {
// TODO Auto-generated method stub
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.selectOne(sql, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return object;
}


@Override
public Object findForObject(String sql) throws Exception {
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.selectOne(sql);
} catch (Exception e) {
throw e;
}
return object;
}


@Override
public long getcount(String sql, Object obj) throws Exception {
SqlSession session = null;
int n = 0;
try {
session = this.getSqlSession();
n = session.selectOne(sql, obj);
} catch (Exception e) {
throw e;
}
return n;
}


@Override
public Object save(String sql, Object paramObj) throws Exception {
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.insert(sql, paramObj);
} catch (Exception e) {
throw e;
}
return object;
}

public int saveBatch(String path, List<?> entitys)throws Exception {
int count = 0;
@SuppressWarnings("unused")
SqlSession session = null;
try {
session = this.getSqlSession();
for(Object entity : entitys) {
count += session.insert(path, entity);
}
} catch (Exception e) {
e.printStackTrace();
count = -1;
}
return count;
}




@Override
public Object update(String sql, Object obj) throws Exception {
// TODO Auto-generated method stub
SqlSession session = null;
Object object = null;
try {
session = this.getSqlSession();
object = session.update(sql, obj);
} catch (Exception e) {
throw e;
}
return object;
}


@Override
public Object updateBatch(String sql, List<Object> list) throws Exception {
// TODO Auto-generated method stub
return null;
}


@Override
public Object updateBatch(String sql, Object[] obj) throws Exception {
// TODO Auto-generated method stub
return null;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值