MyBatis尝鲜
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN""http://ibatis.apache.org/dtd/ibatis-3-config.dtd"><configuration><settings><setting name="cacheEnabled" value="true"/><setting name="lazyLoadingEnabled" value="true"/><setting name="multipleResultSetsEnabled" value="true"/><setting name="useColumnLabel" value="true"/><setting name="useGeneratedKeys" value="false"/><setting name="defaultExecutorType" value="SIMPLE"/><setting name="defaultStatementTimeout" value="25000"/></settings><typeAliases><typeAlias type="org.liufei.ibatis3.model.Admin" alias="Admin"/></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/ibatis?useUnicode=true&characterEncoding=UTF-8" /><property name="username" value="root" /><property name="password" value="liufei" /><property name="poolMaximumActiveConnections" value="20"/><property name="poolMaximumIdleConnections" value="5"/><property name="poolMaximumCheckoutTime" value="20000"/><property name="poolTimeToWait" value="20000"/><property name="poolPingQuery" value="NO PING QUERY SET"/><property name="poolPingEnabled" value="false"/><property name="poolPingConnectionsNotUsedFor" value="0"/></dataSource></environment></environments><mappers><mapper resource="org/liufei/ibatis3/model/AdminMapper.xml" /></mappers></configuration>
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN""http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"><mapper namespace="Admin"><resultMap type="Admin" id="admin"><id property="id" column="id" javaType="java.lang.Integer"/><result property="name" column="name" javaType="java.lang.String"/><result property="password" column="password" javaType="java.lang.String"/></resultMap><insert id="insert" parameterType="Admin" keyProperty="id" useGeneratedKeys="true"><!-- oracle : SELECT STOCKIDSEQUENCE.NEXTVAL AS ID FROM DUAL --><!-- ms sqlserver : SELECT @@IDENTITY AS ID ( 该方法不安全 应当用SCOPE_IDENTITY() 但这个函数属于域函数,需要在一个语句块中执行。 )--><selectKey><![CDATA[SELECT LAST_INSERT_ID() AS ID]]></selectKey><![CDATA[INSERT INTOAdmin(id,name,password)VALUES(#{id, jdbcType=BIGINT},#{name, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR})]]></insert><update id="update" parameterType="Admin"><![CDATA[UPDATE Admin SETname = #{name},password = #{password}WHERE id = #{id}]]></update><delete id="delete" parameterType="Admin"><![CDATA[DELETE FROM Admin]]><where><if test="id != null">id = #{id}</if><if test="name != null">AND name = #{name}</if><if test="password != null">AND password = #{password}</if></where></delete><select id="selectByIdToAdmin" parameterType="int" resultType="Admin">select <include refid="commonColumns"/><![CDATA[from Admin where id = #{id}]]></select><select id="selectByIdToMap" parameterType="int" resultType="admin">select <include refid="commonColumns"/><![CDATA[from Admin where id = #{id}]]></select><select id="selectListByName" parameterType="java.lang.String" resultType="java.util.List">select <include refid="commonColumns"/><![CDATA[from Admin where name = #{name}]]></select><select id="getCounts" parameterType="Admin" resultType="java.lang.Long"><![CDATA[SELECT count(*) from Admin]]><include refid="dynamicWhere"/></select><sql id="columns"><![CDATA[id as admin_id,name as admin_name,password as admin_password]]></sql><sql id="commonColumns"><![CDATA[id, name, password]]></sql><sql id="column"><![CDATA[name, password]]></sql><sql id="dynamicWhere"><where><if test="id != null">id = #{id}</if><if test="name != null">AND name = #{name}</if><if test="password != null">AND password = #{password}</if></where></sql></mapper>
package org.liufei.ibatis3.conf;import java.io.IOException;import java.io.Reader;import java.io.Serializable;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MyBatisSqlSessionFactory implements Serializable {private static final long serialVersionUID = -6077262772667534553L;private final static String RESOURCE_FILE_LOCATION = "Configuration.xml" ;private static String resource = RESOURCE_FILE_LOCATION ;private static SqlSessionFactory sqlSessionFactory ;private static final ThreadLocal<SqlSession> threadLocalSThreadLocal = new ThreadLocal<SqlSession>() ;static{try {Reader reader = Resources.getResourceAsReader(resource) ;MyBatisSqlSessionFactory.sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader) ;} catch (IOException e) {System.out.println("SqlSessionFactory初始化异常: " + e.getLocalizedMessage());}}private MyBatisSqlSessionFactory() {}/** * 获取SqlSession对象 * @return SqlSession */public static SqlSession getSqlSession() {SqlSession sqlSession = (SqlSession) threadLocalSThreadLocal.get() ;if(sqlSession == null){if(sqlSessionFactory == null){rebuildSqlSessionFactory() ;}sqlSession = (sqlSessionFactory != null) ? sqlSessionFactory.openSession() : null ;threadLocalSThreadLocal.set(sqlSession) ;}return sqlSession;}/** * 关闭缓存中的SqlSession对象 */public static void closeSqlSession() {SqlSession sqlSession = (SqlSession) threadLocalSThreadLocal.get() ;threadLocalSThreadLocal.set(null) ;if(sqlSession != null)sqlSession.close() ;}/** * 重置SqlSessionFactory对象 */public static void rebuildSqlSessionFactory(){try {Reader reader = Resources.getResourceAsReader(resource) ;MyBatisSqlSessionFactory.sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader) ;} catch (IOException e) {System.out.println("SqlSessionFactory初始化异常: " + e.getLocalizedMessage());}}/** * 获取SqlSessionFactory对象 * @return SqlSessionFactory */public static SqlSessionFactory getSqlSessionFactory() {if(sqlSessionFactory == null){rebuildSqlSessionFactory() ;}return sqlSessionFactory;}/** * 重置配置文件路径 * @param resource */public static void setResource(String resource) {MyBatisSqlSessionFactory.resource = resource;MyBatisSqlSessionFactory.sqlSessionFactory = null ;}}
package org.liufei.ibatis3.conf;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.ibatis.session.SqlSession;import org.liufei.ibatis3.model.Admin;public class Main {private SqlSession sqlSession ;public Main(){this.sqlSession = MyBatisSqlSessionFactory.getSqlSession() ;}public int insert(Admin admin){int result = 0 ;try{result = this.sqlSession.insert("Admin.insert", admin) ;this.sqlSession.commit() ;}catch (Exception e) {System.out.println("插入异常 : " + e.getLocalizedMessage());this.sqlSession.rollback() ;}return result ;}public int update(Admin admin){int result = 0 ;try{result = this.sqlSession.update("Admin.update", admin) ;this.sqlSession.commit() ;}catch (Exception e) {System.out.println("插入异常 : " + e.getLocalizedMessage());this.sqlSession.rollback() ;}return result ;}public int delete(Admin admin){int result = 0 ;try{result = this.sqlSession.delete("Admin.delete", admin) ;this.sqlSession.commit() ;}catch (Exception e) {System.out.println("插入异常 : " + e.getLocalizedMessage());this.sqlSession.rollback() ;}return result ;}@SuppressWarnings("unchecked")public Map<String, Admin> selectMap(String id){Map<String, Admin> adminMap = new HashMap<String, Admin>() ;adminMap = this.sqlSession.selectMap("Admin.selectByIdToMap", id, "name") ;return adminMap ;}public Admin selectAdmin(int id){return (Admin) this.sqlSession.selectOne("Admin.selectByIdToAdmin", id) ;}@SuppressWarnings("unchecked")public List<Admin> selectList(String name){return this.sqlSession.selectList("Admin.selectListByName", name) ;}public Long getCounts(Admin admin){return (Long) this.sqlSession.selectOne("Admin.getCounts", admin) ;}public static void main(String[] args) {Main maintest = new Main() ;//Admin admin = new Admin(4, "liufeiupdate1", "liufei1229update1222222222222") ;//int i = maintest.insert(admin) ;//int i = maintest.delete(admin) ;//maintest.update(admin) ;Map<String, Admin> adminMap = maintest.selectMap("liufei") ;System.out.println(adminMap.get("liufei"));//Admin adminget = maintest.selectAdmin(10) ;//System.out.println(adminget);List<Admin> admins = maintest.selectList("liufei") ;System.out.println(admins.size());for (Admin admin2 : admins) {System.out.println(admin2);}System.out.println(maintest.getCounts(new Admin(null, "liufei", "liufei1229")));}}