本文的持久化操作使用的是mybatis的sqlSessionTemplate,可用
除了mapper.xml中的sql语句 还可以用这个提供好的类来操作数据库
-
SqlSession sqlSession= sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,
false);
-
//增
-
int result = sqlSession.insert(
"userMapper.insertUsers",user);
-
//删
-
int result = sqlSession.delete(
"userMapper.deleteUsers",
49);
-
//改
-
int result = sqlSession.update(
"userMapper.updateUsers",user);
-
//查
-
List
list = sqlSession.selectList(
"userMapper.queryUsers");
-
User user = sqlSession.selectOne(
"userMapper.queryUserById",
2);
把一个User对象写入数据库,相当于之前一直使用的parameterType="User",它不需要使用dao层,而直接用sqlSessionTemplate去使用mapper.xml里具体的持久化方法。它在spring-mybatis.xml中的配置为:
-
"1.0" encoding=
"UTF-8"?>
-
"http://www.springframework.org/schema/beans"
-
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
-
xmlns:context=
"http://www.springframework.org/schema/context"
-
xmlns:tx=
"http://www.springframework.org/schema/tx"
-
xsi:schemaLocation=
"
-
http://www.springframework.org/schema/beans
-
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-
http://www.springframework.org/schema/context
-
http://www.springframework.org/schema/context/spring-context-3.0.xsd
-
http://www.springframework.org/schema/tx
-
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
-
">
-
-
class=
"org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
-
"ignoreUnresolvablePlaceholders" value=
"true"/>
-
"order" value=
"1"/>
-
"locations">
-
-
classpath:oracle.properties
-
-
-
-
-
-
package=
"cn.richinfo.**" />
-
-
-
"dataSource"
class=
"org.apache.commons.dbcp.BasicDataSource" destroy-method=
"close">
-
"driverClassName" value=
"oracle.jdbc.OracleDriver"/>
-
"url" value=
"${oracle.datasource.url}" />
-
"username" value=
"${oracle.datasource.username}" />
-
"password" value=
"${oracle.datasource.password}" />
-
"maxActive" value=
"${oracle.datasource.maxActive}"/>
-
"maxIdle" value=
"${oracle.datasource.maxIdle}"/>
-
"maxWait" value=
"${oracle.datasource.maxWait}"/>
-
"logAbandoned" value=
"${oracle.datasource.logAbandoned}"/>
-
"removeAbandoned" value=
"${oracle.datasource.removeAbandoned}"/>
-
"removeAbandonedTimeout" value=
"${oracle.datasource.removeAbandonedTimeout}"/>
-
"validationQuery" value=
"select 1 from dual" />
-
-
-
"transactionManager"
class=
"org.springframework.jdbc.datasource.DataSourceTransactionManager">
-
"dataSource" ref=
"dataSource"/>
-
-
-
"transactionManager" />
-
-
-
"sqlSessionFactory"
class=
"org.mybatis.spring.SqlSessionFactoryBean">
-
"dataSource" ref=
"dataSource"/>
-
"mapperLocations" value=
"classpath:cn/richinfo/mapper/*.xml"/>
-
-
-
-
-
-
-
-
-
"sqlSessionTemplate"
class=
"org.mybatis.spring.SqlSessionTemplate" scope=
"prototype">
-
"0" ref=
"sqlSessionFactory"/>
-
-
-
并且在applicationContent.xml中导入
<import resource="classpath*:spring-mybatis.xml" />
mqpper.xml中的写法与spring结合mybatis一直使用的那一套一致。这里要注意的是:
-
namespace=
"userMapper">
-
"insertUser" parameterType=
"cn.data.User">
如上例,在使用中要用"mapperName.methodName"