1. 程式人生 > >MyBatis初學者總結-搭建MyBatis環境步驟

MyBatis初學者總結-搭建MyBatis環境步驟

asr bubuko result tor names new 登錄失敗 apache sys

MyBatis 是一款優秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。MyBatis 只是一個半自動化的ORM實現,需要我們自己寫sql,而不像hibernate那樣,直接定義好實體與數據表的映射就行。

  1. 導入jar包:
  2. 技術分享圖片註意:畫出來的那幾個是用來配置batis的,其他的是寫DBUtils.java用到的
  3. 創建entity包,在
    entity包中創建實體類(UserInfo.java
  4.  1 package entity;
     3 public class UserInfo {
     4     private Integer id;
     5     private String name;
     6     private String password;
     7     public Integer getId() {
     8         return id;
     9     }
    10     public void setId(Integer id) {
    11         this.id = id;
    12     }
    13
    public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getPassword() { 20 return password; 21 } 22 public void setPassword(String password) { 23 this.password = password;
    24 } 25 public UserInfo(Integer id, String name, String password) { 26 super(); 27 this.id = id; 28 this.name = name; 29 this.password = password; 30 } 31 public UserInfo(String name, String password) { 32 super(); 33 this.name = name; 34 this.password = password; 35 } 36 public UserInfo() { 37 super(); 38 // TODO Auto-generated constructor stub 39 } 40 @Override 41 public String toString() { 42 return "UserInfo [id=" + id + ", name=" + name + ", password=" + password + "]"; 43 } 47 }
  5. 創建配置文件(batis-config.xml
  6.  1 <configuration>
     2      <environments default="development">
     3         <environment id="development">
     4             <transactionManager type="JDBC" />
     5             <dataSource type="POOLED">
     6                 <property name="driver" value="${driver}" />
     7                 <property name="url" value="${url}" />
     8                 <property name="username" value="${username}" />
     9                 <property name="password" value="${password}" />
    10             </dataSource>
    11         </environment>
    12     </environments>
    13 </configuration>

    註意:<Configuration>標簽前面需要配置

  7. 1 <!DOCTYPE configuration
    2 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
    4 <configuration>
  8. 創建屬性文件(db.preperties
  9. 1  driver=oracle.jdbc.OracleDriver
    2 url=jdbc:oracle:thin:@localhost:1521:orcl
    3 username=test2
    4 password=123456
  10. 配置文件中(batis-config.xml)加載屬性文件(db.preperties為了獲取屬性文件中定義的值。放置<environments>前面
  11. 1  <properties resource="db.properties">
    2 </properties>
    創建tools包,在tools包中創建工具類(DBUtils.java
  12. 創建tools包,在tools包中創建工具類(DBUtils.java
  13.  1 package tools;
     2 
     3 
     4 import java.io.IOException;
     5 import java.io.Reader;
     6 
     7 import org.apache.ibatis.io.Resources;
     8 import org.apache.ibatis.session.SqlSession;
     9 import org.apache.ibatis.session.SqlSessionFactory;
    10 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    11 
    12 public class DBUtils {
    13     private static SqlSessionFactory factory;
    14     static {
    15         
    16         try {
    17             //讀取配置文件
    18             Reader reader = Resources.getResourceAsReader("batis-config.xml");
    19             //創建SqlSessionFactory
    20             factory=new SqlSessionFactoryBuilder().build(reader);
    21         } catch (IOException e) {
    22             e.printStackTrace();
    23         }
    24     }
    25     /**
    26      * 打開session
    27      * @param flag
    28      * @return
    29      */
    30     public static SqlSession getSession(boolean flag) {
    31         return factory.openSession(flag);
    32     }
    33     /**
    34      * 關閉session
    35      * @param session
    36      */
    37     public static void close(SqlSession session) {
    38         if(session!=null) {
    39             session.close();
    40         }
    41     }
    42     /**
    43      * 事務回滾
    44      * @param session
    45      */
    46     public static void rollback(SqlSession session) {
    47         if(session!=null) {
    48             session.rollback();
    49         }
    50     }
    51     /**
    52      * 事務提交
    53      * @param session
    54      */
    55     public static void commit(SqlSession session) {
    56         if(session!=null) {
    57             session.commit();
    58         }
    59     }
    60 
    61 }
  14. 創建映射文件(dao->>UserInfoMapper接口及定義方法->>創建映射文件)(註意:橙色的id名稱就是接口中定義的方法名稱,兩者要一致
  15.  1 <mapper namespace="dao.UserInfoMapper">
     2     <select id="login" parameterType="UserInfo" resultMap="userInfoResult">
     3         select * from userInfo where name=#{username} and password=#{password}
     4     </select>
     5     
     6     <select id="findAll" resultMap="userInfoResult">
     7         select * from userInfo
     8     </select>
     9     
    10     <insert id="insert">
    11         insert into userInfo(name,password) values(#{username},#{password})
    12     </insert>
    13     
    14     <update id="update" parameterType="UserInfo" >
    15         update userInfo set name=#{username},password=#{password} where id=#{id}
    16     </update>
    17     
    18     <delete id="delete" parameterType="int">
    19         delete from userInfo where id=#{id}
    20     </delete>
    21 </mapper>

    // 註意:上面紅色的是需要在batis-config.xml定義的別名,若不定義,則應寫成:entity.UserInfo
  16. batis-config.xml定義別名:

  17. 1 <typeAliases>
    2     <typeAlias type="entity.UserInfo" alias="UserInfo"/>
    3 </typeAliases> 
    4 
    5 
    6 //(entity.UserInfo:為包名+實體類名 UserInfo:別名)
  18. 上面綠色的,若實體類中的屬性數據庫的屬性沒有對應,則需要進行屬性映射(放在<mapper>標簽下面
  19. 1 <resultMap type="entity.UserInfo" id="userInfoResult">
    2         <id column="id" property="id" />
    3         <result property="username" column="name" />
    4         <result property="password" column="password" />
    5     </resultMap>
  20. 創建測試類(1)采用select方法
  21.  1  @Test
     2     public void testMybatis() {
     3 
     4         SqlSession session = null;
     5         try {
     6             session = DBUtils.getSession(true);
     7             UserInfo userInfo = new UserInfo("TOM", "123456");
     8             UserInfo user = session.selectOne("dao.UserInfoMapper.login", userInfo);
     9             if (user == null) {
    10                 System.out.println("登錄失敗!");
    11             } else {
    12                 System.out.println("登錄成功!");
    13             }
    14         } catch (Exception e) {
    15             e.printStackTrace();
    16         } finally {
    17             if (session != null) {
    18                 DBUtils.close(session);
    19             }
    20         }
    21     }

    采用getMapper()方法

  22.  1  @Test
     2     public void testMapper() {
     3         SqlSession session = null;
     4         try {
     5 
     6             session = DBUtils.getSession(true);
     7             UserInfo userInfo = new UserInfo("TOM", "123456");
     8             UserInfo user = session.getMapper(UserInfoMapper.class).login(userInfo);
     9             if (user == null) {
    10                 System.out.println("登錄失敗");
    11             } else {
    12                 System.out.println("登錄成功");
    13             }
    14         } catch (Exception e) {
    15             e.printStackTrace();
    16         } finally {
    17             if (session != null) {
    18                 DBUtils.close(session);
    19             }
    20         }
    21     }

MyBatis初學者總結-搭建MyBatis環境步驟