Mybatis(一)

MyBatis支持普通的SQL查询、存储过程、高级映射。

借鉴:http://www.cnblogs.com/harrychinese/archive/2012/01/09/learn_mybatis.html#undefined

Mybatis基础配置:

http://blessht.iteye.com/blog/1097005 

1.MyBatis使用自带的数据库连接池!!

2.xml文件中的标签顺序不可改变!!

3.该配置文件可随意取名,在读取时指定路径即可。

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"   
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">  
 4   
 5 <!-- 注意:每个标签必须按顺序写,不然蛋疼的DTD会提示错误:The content of element type "configuration" must match "(properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,plugins?,environments?,mappers?)". -->  
 6 <configuration>  
 7     <!-- 属性配置 -->  
 8     <properties resource="com/mybatisdemo/config/mysql-jdbc-connection.properties">  
 9         <!-- 相同属性:最高优先级的属性是那些作为方法参数的,然后是资源/url 属性,最后是 properties元素中指定的属性 -->  
10         <property name="username" value="root"/>  
11         <property name="password" value="sa"/>  
12     </properties>  
13       
14     <!-- 设置缓存和延迟加载等等重要的运行时的行为方式 -->  
15     <settings>  
16         <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间  -->  
17         <setting name="defaultStatementTimeout" value="25000"/>  
18     </settings>  
19       
20     <!-- 别名 -->  
21     <typeAliases>  
22         <typeAlias alias="UserInfo" type="com.mybatisdemo.entity.UserInfo"/>  
23     </typeAliases>  
24       
25     <environments default="development">  
26         <!-- environment 元素体中包含对事务管理和连接池的环境配置 -->  
27         <environment id="development">  
28             <transactionManager type="JDBC" />  
29             <!-- type分三种:  
30                     UNPOOLED是每次被请求时简单打开和关闭连接   
31                     UNPOOLED的数据源仅仅用来配置以下 4 种属性driver,url,username,password  
32                     POOLED :JDBC连接对象的数据源连接池的实现,不直接支持第三方数据库连接池  
33             -->  
34             <dataSource type="POOLED">  
35                 <property name="driver" value="${driver}" />  
36                 <property name="url" value="${url}" />  
37                 <property name="username" value="${username}" />  
38                 <property name="password" value="${password}" />  
39             </dataSource>  
40         </environment>  
41     </environments>  
42       
43     <!-- ORM映射文件 -->  
44     <mappers>  
45         <mapper resource="com/mybatisdemo/entity/config/UserInfoSqlMap.xml" />  
46     </mappers>  
47       
48       
49 </configuration>   

该配置文件可随意取名,在读取时指定路径即可。。。

1 //读取核心配置文件  
2 Reader reader = Resources.getResourceAsReader("com/mybatisdemo/config/Configuration.xml");  
3 //创建SessionFactory实例  
4 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

 

sql的xml的写法:

http://blog.sina.com.cn/s/blog_6bcb0a8c0100q6ub.html

http://blog.sina.com.cn/s/blog_6bcb0a8c0100q6ud.html

SQL映射的xml:

mapper文件的主要作用就是把SQL统一存放,方便开发人员复用和维护。

 

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <!DOCTYPE mapper       
 3 PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"       
 4 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">       
 5      
 6 <!-- namespace用于java代码调用时识别指定xml的mapper文件 -->  
 7 <mapper namespace="com.mybatisdemo.entity.UserInfo">  
 8     <!-- 配置ORM映射 -->  
 9     <resultMap type="UserInfo" id="user_orm">  
10         <id property="id" column="id"/>  
11         <result property="code" column="code"/>  
12         <result property="name" column="name"/>  
13         <result property="sex" column="sex"/>  
14         <result property="phone" column="phone"/>  
15         <result property="money" column="money"/>  
16     </resultMap>  
17       
18     <!-- 用来定义可重用的SQL代码段 -->  
19     <sql id="demo_sql">  
20         code,name,sex,phone,money  
21     </sql>  
22       
23     <insert id="inser_userInfo" parameterType="UserInfo">  
24         <!-- include 引用可重用的SQL代码段 -->  
25         INSERT INTO USERINFO(<include refid="demo_sql"/>) VALUES(#{code},#{name},#{sex},#{phone},#{money})  
26     </insert>  
27       
28     <update id="update_userInfo" parameterType="UserInfo">  
29         UPDATE USERINFO SET code=#{code} ,name=#{name} ,sex=#{sex} ,phone=#{phone} ,money=#{money} WHERE id=#{id}  
30     </update>  
31     
32     <select id="selectAll_userInfo" useCache="false" flushCache="true" resultMap="user_orm">  
33         SELECT * FROM USERINFO  
34     </select>  
35       
36     <select id="selectById_userInfo" parameterType="int" resultType="UserInfo">  
37         SELECT * FROM USERINFO WHERE id= #{id}  
38     </select>  

前面XML文件已经实现了数据库连接配置和SQL配置,现在就需要用java代码去调用xml配置文件的sql即可实现数据库查询。

MyBatis也有两个核心对象:SqlSessionFactory和SqlSession。

SqlSessionFactory就是获取SqlSession对象的工厂,功能类似于jdbc中加载数据库驱动、创建connection连接,所以该对象保持静态,一直存在。而SqlSession其实就类似于jdbc的connection对象,SqlSession对象就能执行数据库的增删改查操作,大家知道每个数据库连接都是非常珍贵的,所以在使用后尽量及时关闭。

SqlSessionFactory-->创建connection连接;

SqlSession-->就是connection连接。

Util:

 

 1 package com.mybatisdemo.demo;  
 2   
 3 import java.io.IOException;  
 4 import java.io.Reader;  
 5   
 6 import org.apache.ibatis.io.Resources;  
 7 import org.apache.ibatis.session.SqlSession;  
 8 import org.apache.ibatis.session.SqlSessionFactory;  
 9 import org.apache.ibatis.session.SqlSessionFactoryBuilder;  
10   
11 public class SessionFactoryUtil {  
12       
13     private static final String RESOURCE = "com/mybatisdemo/config/Configuration.xml";  
14     private static SqlSessionFactory sqlSessionFactory = null;  
15     private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();  
16   
17     static {  
18         Reader reader = null;  
19         try {  
20             reader = Resources.getResourceAsReader(RESOURCE);  
21         } catch (IOException e) {  
22             throw new RuntimeException("Get resource error:"+RESOURCE, e);  
23         }  
24   
25         sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
26     }  
27       
28     /** 
29      * Function  : 获得SqlSessionFactory 
30      * @author   : bless<505629625@qq.com> 
31      * @return 
32      */  
33     public static SqlSessionFactory getSqlSessionFactory(){     
34         return sqlSessionFactory;     
35     }  
36       
37     /** 
38      * Function  : 重新创建SqlSessionFactory 
39      * @author   : bless<505629625@qq.com> 
40      */  
41     public static void rebuildSqlSessionFactory(){  
42         Reader reader = null;  
43         try {  
44             reader = Resources.getResourceAsReader(RESOURCE);  
45         } catch (IOException e) {  
46             throw new RuntimeException("Get resource error:"+RESOURCE, e);  
47         }  
48   
49         sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);  
50     }  
51       
52     /** 
53      *  
54      * Function  : 获取sqlSession 
55      * @author   : bless<505629625@qq.com> 
56      * @return   : SqlSession 
57      */  
58     public static SqlSession getSession(){  
59         SqlSession session = threadLocal.get();  
60           
61         if(session==null){  
62             if(sqlSessionFactory == null){  
63                 rebuildSqlSessionFactory();  
64             }  
65             //如果sqlSessionFactory不为空则获取sqlSession,否则返回null  
66             session = (sqlSessionFactory!=null) ? sqlSessionFactory.openSession(): null;  
67         }  
68           
69         return session;  
70     }  
71       
72     /** 
73      * Function  : 关闭sqlSession 
74      * @author   : bless<505629625@qq.com> 
75      */  
76     public static void closeSession(){  
77         SqlSession session = threadLocal.get();  
78         threadLocal.set(null);  
79         if(session!=null){  
80             session.close();  
81         }  
82     }  
83 }  

 

使用:

 1 package com.mybatisdemo.demo;  
 2   
 3   
 4 import java.util.List;  
 5   
 6 import org.apache.ibatis.session.RowBounds;  
 7 import org.apache.ibatis.session.SqlSession;  
 8 import com.mybatisdemo.entity.UserInfo;  
 9   
10 public class UserInfoDao {  
11           
12     @SuppressWarnings("unchecked")  
13     public List<UserInfo> findAll(){  
14         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
15         List<UserInfo> lstUser = null;  
16         lstUser = session.selectList("com.mybatisdemo.entity.UserInfo.selectAll_userInfo");  
17         session.close();  
18         return lstUser;  
19     }  
20       
21     @SuppressWarnings("unchecked")  
22     public List<UserInfo> findList(int pageNo,int pageSize){  
23         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
24         List<UserInfo> lstUser = null;  
25         lstUser = session.selectList("com.mybatisdemo.entity.UserInfo.selectAll_userInfo", null, new RowBounds((pageNo-1)*pageSize, pageSize));  
26         session.close();  
27         return lstUser;  
28     }  
29       
30     public UserInfo findById(int id){  
31         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
32         UserInfo user =  (UserInfo) session.selectOne("selectById_userInfo", id);  
33         session.close();  
34         return user;  
35     }  
36       
37     public void insert(UserInfo user){  
38         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
39         session.insert("com.mybatisdemo.entity.UserInfo.inser_userInfo", user);  
40         session.commit();  
41         session.close();  
42     }  
43       
44     public void update(UserInfo user){  
45         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
46         session.update("com.mybatisdemo.entity.UserInfo.update_userInfo", user);  
47         session.commit();  
48         session.close();  
49     }  
50       
51     public static void main(String[] args) {  
52         List<UserInfo> lst = new UserInfoDao().findList(3,2);  
53         for (UserInfo userInfo : lst) {  
54             System.out.println(userInfo.getId()+" "+userInfo.getName());  
55         }  
56     }  
57 }  

selectList中传入的参数:其实这个"com.mybatisdemo.entity.UserInfo.selectAll_userInfo"就是从前面mapper配置文件中去找对应的sql语句,"com.mybatisdemo.entity.UserInfo"表示配置文件的namespace,"selectAll_userInfo"表示配置文件具体的select标签,update和insert类似。

 

 

 

  1. package com.mybatisdemo.demo;  
  2.   
  3.   
  4. import java.util.List;  
  5.   
  6. import org.apache.ibatis.session.RowBounds;  
  7. import org.apache.ibatis.session.SqlSession;  
  8. import com.mybatisdemo.entity.UserInfo;  
  9.   
  10. public class UserInfoDao {  
  11.           
  12.     @SuppressWarnings("unchecked")  
  13.     public List<UserInfo> findAll(){  
  14.         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
  15.         List<UserInfo> lstUser = null;  
  16.         lstUser = session.selectList("com.mybatisdemo.entity.UserInfo.selectAll_userInfo");  
  17.         session.close();  
  18.         return lstUser;  
  19.     }  
  20.       
  21.     @SuppressWarnings("unchecked")  
  22.     public List<UserInfo> findList(int pageNo,int pageSize){  
  23.         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
  24.         List<UserInfo> lstUser = null;  
  25.         lstUser = session.selectList("com.mybatisdemo.entity.UserInfo.selectAll_userInfo"nullnew RowBounds((pageNo-1)*pageSize, pageSize));  
  26.         session.close();  
  27.         return lstUser;  
  28.     }  
  29.       
  30.     public UserInfo findById(int id){  
  31.         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
  32.         UserInfo user =  (UserInfo) session.selectOne("selectById_userInfo", id);  
  33.         session.close();  
  34.         return user;  
  35.     }  
  36.       
  37.     public void insert(UserInfo user){  
  38.         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
  39.         session.insert("com.mybatisdemo.entity.UserInfo.inser_userInfo", user);  
  40.         session.commit();  
  41.         session.close();  
  42.     }  
  43.       
  44.     public void update(UserInfo user){  
  45.         SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();  
  46.         session.update("com.mybatisdemo.entity.UserInfo.update_userInfo", user);  
  47.         session.commit();  
  48.         session.close();  
  49.     }  
  50.       
  51.     public static void main(String[] args) {  
  52.         List<UserInfo> lst = new UserInfoDao().findList(3,2);  
  53.         for (UserInfo userInfo : lst) {  
  54.             System.out.println(userInfo.getId()+" "+userInfo.getName());  
  55.         }  
  56.     }  
  57. }  
posted @ 2016-08-29 21:58  重重的博客园  阅读(196)  评论(0编辑  收藏  举报