标签:语句 映射 insert 规则 数据库 单例 XML into get
使用MyBatis 肯定是要生成 SqlSessionFactory
1.通过读取xml 配置文件用SqlSessionFactoryBuilder 生成
2.通过代码用 SqlSessionFactoryBuilder 生成
SqlSessionFactory的作用?
sqlSessionFactory 唯一的作用就是生产 MyBatis的核心接口对象SqlSession
一般采用单例模式处理它
SqlSession的作用?
SqlSession 的作用类似一个JDBC中的 Connection 对象代表着一个连接资源的启用。
具体
如何获得 SqlSession?
SqlSession sqlSession = SqlSessionFactoty.opensession();
SQL Mapper (映射器)的作用?
如何实现映射器?
XML 方式创建映射器
1.映射器接口
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); }
2.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.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>
3.在 mybatis-config.xml 中引入XML配置文件
<mappers> <mapper resource="com/ssm/mapper/RoleMapper.xml"/> </mappers>
注解实现映射器
1.映射器接口
public interface RoleMapper2 { @Select("select id, role_name as roleName, note from t_role where id=#{id}") public Role getRole(Long id); }
2..在 mybatis-config.xml 中引入对应的class路径
<mappers> <mapper class="com.ssm.mapper.RoleMapper2"/> </mappers>
如何获取Mapper接口?
通过SqlSession 获取Mapper 接口,并发送SQL
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); Role role = roleMapper.getRole(1L);
标签:语句 映射 insert 规则 数据库 单例 XML into get
原文地址:https://www.cnblogs.com/wayoufeidie/p/11809115.html