MyBatis3新手上路
?
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.0.1</version></dependency><dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version></dependency><dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.0.0-RC3</version></dependency><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version></dependency>?
<?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 设置应用Spring注解扫描的包路径,我们后面的DAO会使用注解方式@Component配置Bean --> <context:component-scan base-package="com.shansun.mybatis.model"></context:component-scan> <!-- 设置数据源信息 --> <bean id="dataSourceImpl" ref="dataSourceImpl"/> <!-- 这里指定Mapper路径的配置信息 --> <property name="configLocation" value="classpath:ibatis/sqlMapConfig.xml"/> </bean> </beans>
<?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> <mappers> <mapper resource="ibatis/UserMapper.xml" /> </mappers></configuration>
字段名
类型
长度
备注
Id
Bigint
20
主键
User_id
Bigint
20
用户编号
User_nick
Varchar
20
用户昵称
Sex
Tinyint
1
性别:0-男,1-女
Age
Tinyint
3
年龄
Gmt_create
Date
?
创建时间
Gmt_modified
Date
?
修改时间
package com.shansun.mybatis.model; import java.util.Date; public class UserDO { private Long id; private Long userId; private String userNick; private Byte sex; private Byte age; private Date gmtCreate; private Date gmtModified; ......setter/getter......}
<?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="com.shansun.mybatis.model.UserMapper"> <resultMap id="ibatorgenerated_BaseResultMap" type="com.shansun.mybatis.model.UserDO"> <result column="id" property="id" jdbcType="BIGINT" /> <result column="user_id" property="userId" jdbcType="BIGINT" /> <result column="user_nick" property="userNick" jdbcType="BIGINT" /> <result column="sex" property="sex" jdbcType="SMALLINT" /> <result column="age" property="age" jdbcType="SMALLINT" /> <result column="gmt_create" property="gmtCreate" jdbcType="TIMESTAMP" /> <result column="gmt_modified" property="gmtModified" jdbcType="TIMESTAMP" /> </resultMap> <sql id="commonColumns"> id, user_id, user_nick, sex, age, gmt_create, gmt_modified </sql> <select id="queryUserByUID" parameterType="Long" resultMap="ibatorgenerated_BaseResultMap"> select <include refid="commonColumns"/> from user where user_id=#{userId} limit 1; </select></mapper>
package com.shansun.mybatis.model; public interface UserDAO { public UserDO queryUserByUID(Long userId);}
package com.shansun.mybatis.model; import org.mybatis.spring.support.SqlSessionDaoSupport;@Componentpublic class UserDAOImpl extends SqlSessionDaoSupport implements UserDAO { @Override public UserDO queryUserByUID(Long userId) { return (UserDO) getSqlSession().selectOne("com.shansun.mybatis.model.UserMapper.queryUserByUID", userId); }}
public class Main { public static void main(String[] args) { long userId = 198805; ApplicationContext aContext = new FileSystemXmlApplicationContext("classpath:ibatis-test-ds.xml"); UserDAO userMapper = aContext.getBean(UserDAO.class); UserDO userDO = userMapper.queryUserByUID(userId); System.out.println(userDO.toString()); }}
By?Mr.Chris
<?xml version="1.0" encoding="UTF-8"?><!-- Copyright 2010 The myBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd" default-autowire="byName"> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@**"/> <property name="username" value="**"/> <property name="password" value="**"/> <property name="maxActive" value="150"/> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" ref="dataSource" /> </bean> <!-- enable component scanning (beware that this does not enable mapper scanning!) --> <context:component-scan base-package="com.apeksys.qms.service" /> <context:component-scan base-package="com.apeksys.qms.action" /> <!-- enable autowire <context:annotation-config /> --> <!-- enable transaction demarcation with annotations --> <tx:annotation-driven /> <aop:aspectj-autoproxy/><!-- propagration 表示事务传播特性, 使用required 时表示:当检测到以create开关的方法时先看有没有开启事务,如果开启事务则放进事务中去,如果没有则新建一个事务放进去; read-only="true" 数据库的只读属性,当该方法在读时,其它方法不能再去写,保证一个事务的完整性; --> <tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="create*" propagation="REQUIRED" read-only="true" rollback-for="Throwable"/><tx:method name="update*" propagation="REQUIRED" read-only="true" rollback-for="Throwable"/><tx:method name="delete*" propagation="REQUIRED" read-only="true" rollback-for="Throwable"/><tx:method name="import*" propagation="REQUIRED" read-only="true" rollback-for="Throwable"/><!-- 除了上面的方法,其它方法全部是只读 --><tx:method name="*" read-only="true"/></tx:attributes> </tx:advice> <aop:config proxy-target-expression="execution(* com.apeksys.qms.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/> </aop:config> <!-- define the SqlSessionFactory, notice that configLocation is not needed when you use MapperFactoryBean --> <bean id="sqlSessionFactory" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- scan for mappers and let them be autowired --> <bean value="com.apeksys.qms.mapper.dao" /> </bean> <!-- <bean id="rootService" ref="sysUserInfoService"/> </bean> --></beans>
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!-- 节点加载顺序context-param > listener > filter > servlet --><display-name>Quanlity Management System</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- <listener> <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class> </listener> --><filter><filter-name>loginFilter</filter-name><filter-class>com.apeksys.qms.support.LoginFilter</filter-class></filter><filter-mapping><filter-name>loginFilter</filter-name><url-pattern>*.action</url-pattern></filter-mapping><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>*.action</url-pattern></filter-mapping><servlet><servlet-name>JSONRPCServlet</servlet-name><servlet-class>com.metaparadigm.jsonrpc.JSONRPCServlet</servlet-class><load-on-startup>2</load-on-startup> </servlet><servlet-mapping><servlet-name>JSONRPCServlet</servlet-name><url-pattern>/JSON-RPC</url-pattern></servlet-mapping> <taglib><taglib-uri>/page</taglib-uri><taglib-location>/WEB-INF/pageTag.tld</taglib-location></taglib> <!-- <error-page><exception-type>java.lang.Exception</exception-type><location>/system/error.jsp</location></error-page><error-page><error-code>404</error-code><location>/system/error.jsp</location></error-page><error-page><error-code>500</error-code><location>/system/error.jsp</location></error-page> --><welcome-file-list> <welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
# Rules reminder: # DEBUG < INFO < WARN < ERROR < FATAL # Global logging configuration log4j.rootLogger=INFO, stdout ## Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %5p %C: %m%n log4j.logger.org.apache.ibatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUGpublic SqlSource parse(String originalSql, Class parameterType) { ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType); GenericTokenParser parser = new GenericTokenParser("#{", "}", handler); String sql = parser.parse(originalSql); return new StaticSqlSource(configuration, sql, handler.getParameterMappings());}<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.15</version><scope>provided</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.5.6</version></dependency>
# Rules reminder: # DEBUG < INFO < WARN < ERROR < FATAL # Global logging configuration log4j.rootLogger=INFO, stdout ## Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %5p %C: %m%n log4j.logger.org.apache.ibatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG