Mybatis简单应用

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();
			}
		}
	}
}

  

posted on 2018-11-03 16:22  卖肾割阑尾  阅读(98)  评论(0编辑  收藏  举报

导航