mybatis深入學習一
阿新 • • 發佈:2018-12-09
Mybati核心元件:
SqlSessionFactoryBuilder(構造器):它關於根據配置資訊或者程式碼來生成SqlSessionFactory(工廠介面)。
SqlSessionFactory:依靠工廠來生成SqlSession(會話)。
SqlSession:是一個即可以傳送SQL去執行並返回結果,也可以獲取Mapper的介面。
SQL Mapper:它是Mybatis新設計的元件。它是由Java介面和xml檔案(或註解)構成的,需要給出對應的SQL和對映規則。它負責傳送SQL去執行,並返回結果。
JDBC程式設計:
public class JdbcExample { private Connection getConnection(){ Connection connection=null; try{ //載入驅動 Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/mybatis?zeroDateTime Behavior=convertToNull"; String user="root"; String password="root"; //建立連線物件 connection=DriverManager.getConnection(url,user,password); }catch(ClassNotFoundException | SQLException ex){ ex.printstack(); return null; } return connection; } public Role getRole(Long id){ Connection connection=getConnection(); PreparedStatement ps=null; ResultSet rs=null; try{ //建立執行語句 ps=connection.prepareStatement("select id,role_name,note from t_role where id=?"); //執行語句注入值 ps.setLong(1,id); //執行語句產生結果集 rs=ps.executeQuery(); while(rs.next()){ Long roleId=rs.getLong("id"); String userName=rs.getString("role_name"); String note=rs.getString("note"); Role role=new Role(); role.setId(id); role.setRoleName(userName); role.setNote(note); return role; } }catch(SQLException ex){ ex.printstack(); }finally{ this.close(rs,ps,connection); } return null; } //關閉資料庫連線 private void close(ResultSet rs,Statement stmt,Connection connection){ try{ if(rs!=null && !rs.isClosed()){ rs.close(); } if(stmt!=null && !stmt.isClosed()){ stmt.close(); } if(connection!=null && !connection.isClosed()){ connection.close(); } }catch(SQLException ex){ ex.printstack(); } } public static void main(String[]args){ JdbcExample example=new JdbcExample(); ROle role=example.getRole(1L); System.print.out("role_name="+role.getRoleName()); } }
每個Mybatis的應用都是以SqlSessionFactory的例項為中心。Mybatis提供兩種模式建立SqlSessionFactory:
一.xml配置的方式:mybatis_config.xml
<?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> <!--定義別名--> <typeAliases> <typeAlias alias="role" type="com.learn.chapter2.po.Role"/> </typeAliases> <!--定義資料庫資訊,預設使用development資料庫構建環境--> <enviroments default="developments"> <enviroment id="development"> <!--採用jdbc事務管理--> <transactionManager type="JDBC"/> <!--配置資料庫連線資訊--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </enviroment> </enviroments> <!--定義對映器--> <mappers> <mapper resource="com/learn/chapter2/mapper/roleMapper.xml"/> </mappers> </configuration>
對映檔案:roleMapper.xml
<?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.learn.mybatis.chapter1.mapper.RoleMapper"> <select id="getRole" parameterType="long" resultType="com.learn.mybatis.chapter1.pojo.Role> <!--這裡的SQL沒有給出對映規則的原因是:我們使用的SQL列名和POJO的屬性名保持一致,這個時候Mybatis會自動提供對映規則,所以省去了這部分的配置工作--> select id,role_name as roleName,note from t_role where id=#{id} </select>
利用如上配置檔案,我們的實現程式碼:
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=null;
sqlSessionFactory=new SqlSessionFactoryBuilder().buid(inputStream);
二.使用程式碼方式構建:
//構建資料庫連線池
PooledDateSource dateSource=new PooledDateSource();
dateSource.setDriver("com.mysql.jdbc.Driver");
dateSource.setUrl("jdbc:mysql://localhost:3306/mybatis");
dateSource.setUsername("root");
dateSource.setPassword("learn");
//構建資料庫事務方式
TranscationFactory transactionFactory=new JdbcTransactionFactory();
//建立資料庫執行環境
Environment enviroment=new Enviroment("development",transactionFactory,dataSource);
//構建Configuration物件
Configuration configuration=new Configuration(enviroment);
//註冊一個Mybatis上下文別名
configuration.getTypeAliasRegistry().registerAlias("role",Role.class);
//加入一個對映器
configuration.addMapper(RoleMapper.class);
//使用SqlSessionFactoryBuilder 構建SqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(configuration);