过去做过一些基于springhibernate整合应用的实例本人感觉spring与hibernate最好的结合就是泛型Dao的实现代码量节省了一半而且业务逻辑一目了然
后来做别的系统时候考虑过这样的框架但是数据库结构如果不固定动态生成的东西比较多这个时候只好放弃了hibernate而选择了同样具有orm性能的ibatis下面就spring与ibatis的结合相关配置做下说明(如有不同意见希望交流)
首先spring和ibatis具体下载和安装就不多说了直接切入正题
Spring框架下的ibatis应用特别是在容器事务管理模式下的ibatis应用开发
部署如下
首先spring配置文件
Spring_basexml
<?xml version= encoding=UTF ?>
<!DOCTYPE beans PUBLIC //SPRING//DTD BEAN//EN beansdtd>
<beans defaultlazyinit=true>
<! 配置数据源 >
<bean id=dataSource class=monsdbcpBasicDataSource destroymethod=close>
<property name=driverClassName>
<value>netsourceforgejtdsjdbcDriver</value>
</property>
<property name=url>
<value>jdbc:jtds:sqlserver://localhost:/test</value>
</property>
<property name=username>
<value>sa</value>
</property>
<property name=password>
<value>sa</value>
</property>
<property name=maxActive>
<value></value>
</property>
<property name=maxIdle>
<value></value>
</property>
<property name=maxWait>
<value></value>
</property>
</bean>
/////////////////// dataSource配置你的数据源连接
<bean id=sqlMapClient
class=orgspringframeworkormibatisSqlMapClientFactoryBean>
<property name=configLocation>
<value>SqlMap_configxml</value>
</property>
<property name=dataSource><! 从指定dataSource中获取数据源 亦可把该定义放到每个自定义Dao中>
<ref bean=dataSource />
</property>
</bean>
//////////////////// sqlMapClient集成ibatis配置文件和把数据源与ibatis相关联
<! 配置事务管理 >
<bean id=transactionManager class=orgspringframeworkjdbcdatasourceDataSourceTransactionManager>
<property name=dataSource>
<ref local=dataSource />
</property>
</bean>
///////////////// transactionManager:配置事务管理
<!公共组件>
<import resource=spring_otherxml />
////////////把用户自定义Bean与基本bean分开集成进去spring_otherxml文件
</beans>
以上是spring 把一些ibatis相关配置集成到自己的配置文件里面
Spring_otherxml
<?xml version= encoding=UTF?>
<!DOCTYPE beans PUBLIC //SPRING//DTD BEAN//EN beansdtd>
<beans>
<bean id=userService class=comuserUserServiceImpl>
<property name=transactionManager>
<ref bean=transactionManager />
</property>
<property name=userDao>
<ref local=userDao />
</property>
</bean>
////////////////////////使用service管理所有用户自定义bean和Dao操作用来设置事务回滚线程安全等
<bean id=userDao class=comuserdaoUserDaoImpl>
<property name=sqlMapClient ref=sqlMapClient/>
</bean>
///////////////用户自定义Dao操作因spring_basexml中sqlMapClient已经把dataSource包含故dataSource不再声明如果该操作需要别的数据连接可加入例如
////////<property name=dataSource ref=dataSource/>//////////
</beans>
Spring_otherxml存放用户自定义bean
SqlMap_configxml
<?xml version= encoding=UTF ?>
<!DOCTYPE sqlMapConfig
PUBLIC ////DTD SQL Map Config //EN
mapconfigdtd>
<sqlMapConfig>
<settings lazyLoadingEnabled=true
useStatementNamespaces=true
enhancementEnabled=true
errorTracingEnabled=true
/>
/////////////定义ibatis相关操作参数例如延迟加载命名空间是否生效是否打开缓存调试阶段出错信息反馈等等
<sqlMap resource=com/user/userxml />
//////////////包含用户的相关操作xml文件
</sqlMapConfig>
Userxml
<?xml version= encoding=UTF ?>
<!DOCTYPE sqlMap
PUBLIC ////DTD SQL Map //EN
mapdtd>
<sqlMap namespace=User>
<typeAlias alias=user type=comuserUser /><! obj >
<! get user >
<select id=getUser
parameterClass=javalangString
resultClass=user>
<![CDATA[
select
id
name
sex
from
t_user
where name like #name#
]]>
</select>
<! update user >
<update id=updateUser parameterClass=user>
<![CDATA[
update t_user
set
name=#name#
sex=#sex#
where id = #id#
]]>
</update>
<insert id=insertUser parameterClass=user>
<![CDATA[
insert into t_user(
id
name
sex)
values(
#id#
#name#
#sex#
)
]]>
</insert>
<delete id=deleteUser parameterClass=javalangString>
<![CDATA[
delete from t_user
where id = #value#
]]>
</delete>
<select id=selectUser resultClass=user>
<![CDATA[
select * from t_user order by id desc
]]>
</select>
</sqlMap>
该配置文件属性就不多了用户可在网上搜一堆够看了
针对spring_otherxml 里面的用户自定义bean如下
UserDaojava 接口
package comuserdao;
import javautilList;
import comuserUser;
public interface UserDao {
public User getUser(String name);
public void updateUser(User user);
public List selectUser();
public void insertUser(User user);
}
UserDaoImpljava 实现类
package comuserdao;
import javautilList;
import orgspringframeworkormibatissupportSqlMapClientDaoSupport;
import comuserUser;
public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {
//private static Logger log = LoggergetLogger(UserDaoImplclass);
public User getUser(String name) {
return (User) thisgetSqlMapClientTemplate()queryForObject(UsergetUsername);
}
public void updateUser(User user) {
thisgetSqlMapClientTemplate()update(UserupdateUser user);
}
public List selectUser() {
return thisgetSqlMapClientTemplate()queryForList(UserselectUser);
}
public void insertUser(User user) {
thisgetSqlMapClientTemplate()insert(UserinsertUser user);
}
}
现在大家也许看到这里觉得就差不多了该Dao方法差不多全了可以进行操作了其实不然下面我载自官方的一段
Spring提供两种方式的编程式事务管理分别是使用TransactionTemplate和直接使用PlatformTransactionManager
ⅰ TransactionTempale采用和其他Spring模板如JdbcTempalte和HibernateTemplate一样的方法它使用回调方法把应用程序从处理取得和释放资源中解脱出来如同其他模板TransactionTemplate是线程安全的
所以我们下面我们要再封装一层以实现线程是安全的这就是我们在spirng_otherxml里面的那段配置实现
baseServicejava
package combase;
import orgspringframeworktransactionsupportTransactionTemplate;
/**
* 工厂的基础类.
* @author 刘玉华
* @time
*/
public class BaseService extends TransactionTemplate{
private static final long serialVersionUID = L;
}
serviceFactoryjava
package combase;
import orgspringframeworkbeansfactoryBeanFactory;
import orgntextsupportClassPathXmlApplicationContext;
import comuserdaoUserDao;
/**
* 数据操作工厂所有的数据操作都从该工厂中获得
* @author 刘玉华
* @time
*/
public class ServiceFactory {
private static BeanFactory factory = null;
static {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {spring_basexml});
factory = (BeanFactory) context;
}
/**
* 获得用户服务类
* @return 用户服务
*/
public static UserDao getUserService(){
return (UserDao) factorygetBean(userService);
}
}
我们所需要做的就是继承Baseservicejava 以实现tx管理
UserServicejava
package comuser;
import javautilList;
public interface UserService {
public User getUser(final String name);
public void updateUser(final User user);
public List selectUser();
public void insertUser(final User user);
}
UserServiceImpljava 用户服务实现类
package comuser;
import javautilList;
import orgspringframeworktransactionTransactionStatus;
import orgspringframeworktransactionsupportTransactionCallback;
import combaseBaseService;
import comuserdaoUserDao;
public class UserServiceImpl extends BaseService implements UserDao {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
thisuserDao = userDao;
}
public List selectUser() {
Object obj = execute(new TransactionCallback(){
public Object doInTransaction(TransactionStatus status) {
return userDaoselectUser();
}
});
return (List)obj;
}
public User getUser(final String name){
Object obj = execute(new TransactionCallback(){
public Object doInTransaction(TransactionStatus status) {
// TODO Autogenerated method stub
return userDaogetUser(name);
}
});
return (User) obj;
}
public void insertUser(final User user) {
Object obj = execute(new TransactionCallback(){
public Object doInTransaction(TransactionStatus status) {
userDaoinsertUser(user);
return null;
}
});
}
public void updateUser(final User user) {
Object obj = execute(new TransactionCallback(){
public Object doInTransaction(TransactionStatus arg) {
userDaoupdateUser(user);
return null;
}
});
}
}
这样我们就把相关操作实现事务控制了
数据表建立
create table t_user(
id int null
name varchar() null
sex int null
)
这样我们在以后调用方式为
测试类
package comuserjunit;
import javautilList;
import combaseServiceFactory;
import comuserUser;
import comuserdaoUserDao;
import commonLogger;
public class UserTest {
private static Logger log = LoggergetLogger(UserTestclass);
public static void main(String args[]){
UserDao service = ServiceFactorygetUserService();
User user=null;
int i = ;
switch (i) {
case :
usersetId();
usersetName();
usersetSex();
serviceupdateUser(user);
Systemoutprintln(usergetName()+ +usergetSex());
break;
case :
try {
user = servicegetUser();
} catch (Exception e) {
logdebug(出错了+egetMessage());
}
Systemoutprintln(usergetId());
case :
List<User> ls = serviceselectUser();
for (int j = ; j < lssize(); j++) {
Systemoutprintln(lsget(j)getId()+====+lsget(j)getName());
}
case :
List<User> ls = serviceselectUser();
for (int j = ; j < lssize(); j++) {
user = lsget(j);
Systemoutprintln(usergetId()+usergetName()+usergetSex()+usergetAddress());
}
for (int j = ; j < ; j++) {
usersetId(usergetId()+);
serviceinsertUser(user);
}
default:
break;
}
}
}