Mybatis簡單應用

來源:互聯網
上載者:User

標籤:his   utils   tsql   資料庫連接   OLE   type   pac   chap   組件   

Mybatis的核心組件:

  • SqlSeeeionFactoryBuilder (構建器):它會根據配置或者代碼來產生SqlSessionFactory,採用的是分布構建的Builder模式;
  • SqlSessionFactory:依靠它來產生SqlSession,使用的是原廠模式。
  • SqlSession(會話)發送SQL執行並返回結果,也可以擷取Mapper介面。
  • SQL Mapper(映射器): 由一個java介面和XML檔案(或註解)構成,需要給出SQL的映射規則。它負責發送SQL去執行返回結果。

1.使用XML:mybatis-config.xml建立SqlSessionFactory的配置;

<?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.ssm.chapter3.pojo.Role"/>  </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/ssm"/>        <property name="username" value="root"/>        <property name="password" value="admin123"/>      </dataSource>    </environment>  </environments>  <!-- 對應檔 -->  <mappers>    <mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>    <mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/>   </mappers></configuration>

1.1 使用代碼或xml建立SqlSessionFactory

package com.learn.ssm.chapter3.utils;import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.datasource.pooled.PooledDataSource;import org.apache.ibatis.io.Resources;import org.apache.ibatis.mapping.Environment;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.apache.ibatis.transaction.TransactionFactory;import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;import com.learn.ssm.chapter3.mapper.RoleMapper;import com.learn.ssm.chapter3.mapper.RoleMapper2;import com.learn.ssm.chapter3.pojo.Role;public class SqlSessionFactoryUtils {    private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;    private static SqlSessionFactory sqlSessionFactory = null;    private SqlSessionFactoryUtils() {    }    public static SqlSessionFactory getSqlSessionFactory() {        synchronized (LOCK) {            if (sqlSessionFactory != null) {                return sqlSessionFactory;            }            String resource = "mybatis-config.xml";            InputStream inputStream;            try {                inputStream = Resources.getResourceAsStream(resource);                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);            } catch (IOException e) {                e.printStackTrace();                return null;            }            return sqlSessionFactory;        }    }            //代碼產生SqlSessionFactory    public static SqlSessionFactory getSqlSessionFactory2() {        synchronized (LOCK) {            //資料庫連接池資訊            PooledDataSource dataSource = new PooledDataSource();            dataSource.setDriver("com.mysql.jdbc.Driver");            dataSource.setUsername("root");            dataSource.setPassword("admin123");            dataSource.setUrl("jdbc:mysql://localhost:3306/ssm");            dataSource.setDefaultAutoCommit(false);            //採用MyBatis的JDBC事務方式            TransactionFactory transactionFactory = new JdbcTransactionFactory();            Environment environment = new Environment("development", transactionFactory, dataSource);            //建立Configuration對象            Configuration configuration = new Configuration(environment);            //註冊一個MyBatis上下文別名            configuration.getTypeAliasRegistry().registerAlias("role", Role.class);            //加入一個映射器            configuration.addMapper(RoleMapper.class);            configuration.addMapper(RoleMapper2.class);            //使用SqlSessionFactoryBuilder構建SqlSessionFactory            sqlSessionFactory =                 new SqlSessionFactoryBuilder().build(configuration);            return sqlSessionFactory;             }    }    public static SqlSession openSqlSession() {        if (sqlSessionFactory == null) {            getSqlSessionFactory();        }        return sqlSessionFactory.openSession();    }}

2. 映射器,由一個java介面和XML檔案(或註解)構成

首先定義一個POJO

package com.learn.ssm.chapter3.pojo;public class Role {    private Long id;    private String roleName;    private String note;    /** setter and getter **/    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getRoleName() {        return roleName;    }    public void setRoleName(String roleName) {        this.roleName = roleName;    }    public String getNote() {        return note;    }    public void setNote(String note) {        this.note = note;    }}

2.1, 介面和XML實現映射

映射器介面:

public interface RoleMapper {    public int insertRole(Role role);    public int deleteRole(Long id);    public int updateRole(Role role);    public Role getRole(Long id);    public List<Role> findRoles(String roleName);}

在XML建立SqlSession中有這樣代碼

<mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>
引入XML(RoleMapper.xml)建立映射器(insert/select/update/delete)代表增/查/改/刪
id 代表RoleMapper中方法名字
parameterType代表傳入參數類型
resultType代表傳回值 "role"是別名,代表<typeAlias alias="role" type="com.learn.ssm.chapter3.pojo.Role"/>
<?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.ssm.chapter3.mapper.RoleMapper">    <insert id="insertRole" parameterType="role">        insert into t_role(role_name, note) values(#{roleName}, #{note})    </insert>    <delete id="deleteRole" parameterType="long">        delete from t_role where id= #{id}    </delete>    <update id="updateRole" parameterType="role">        update t_role set role_name = #{roleName}, note = #{note} where id= #{id}    </update>    <select id="getRole" parameterType="long" resultType="role">        select id,        role_name as roleName, note from t_role where id = #{id}    </select>    <select id="findRoles" parameterType="string" resultType="role">        select id, role_name as roleName, note from t_role        where role_name like concat(‘%‘, #{roleName}, ‘%‘)    </select></mapper>

 

2.2註解實現映射器

XML中引入Mapper:

 <mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/> 
public interface RoleMapper2 {        @Select("select id, role_name as roleName, note from t_role where id=#{id}")    public Role getRole(Long id);        @Insert("insert into t_role(role_name,note) values(#{roleName},#{note})")    public void insertRole(Role role);}

 註解不易於維護

3. 測試:

public class Chapter3Main {public static void main(String[] args) {testRoleMapper();testRoleMapper2();}//xml 測試private static void testRoleMapper() {Logger log = Logger.getLogger(Chapter3Main.class);SqlSession sqlSession = null;try {sqlSession = SqlSessionFactoryUtils.openSqlSession();RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);Role role = roleMapper.getRole(1L);Role r1 = new Role();r1.setRoleName("testRole name");r1.setNote("note...");roleMapper.insertRole(r1);sqlSession.commit();log.info(role.getRoleName());}catch(Exception ex){sqlSession.rollback();}finally {if (sqlSession != null) {sqlSession.close();}}}//註解SQL測試private static void testRoleMapper2() {Logger log = Logger.getLogger(Chapter3Main.class);SqlSession sqlSession = null;try {sqlSession = SqlSessionFactoryUtils.openSqlSession();RoleMapper2 roleMapper2 = sqlSession.getMapper(RoleMapper2.class);Role role = roleMapper2.getRole(1L);Role r1 = new Role();r1.setRoleName("testRole name map2");r1.setNote("note...");roleMapper2.insertRole(r1);sqlSession.commit();log.info(role.getRoleName());} catch(Exception ex){sqlSession.rollback();}finally {if (sqlSession != null) {sqlSession.close();}}}}

  

Mybatis簡單應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.