MyBatis初探一

1、MyBatis介绍

mybatis(持久层框架3.2.6 or 3.2.7)简单执行流程html

>1.SqlMapConfig.xml(全局配置文件),配置数据源,事务和运行环境等java

>2.配置映射文件(编写SQL语句):mapper.xml...mysql

>3.SqlSessionFactory(会话工厂)--create--->SqlSession(会话)操做数据库发送SQL语句--->Executor(执行器接口,包含基本执行器和缓存执行器)SqlSession内部经过执行器操做数据库--->MappedStatement(底层封装对象)对SQL语句,输入参数,输出结果类型sql

参考资料:数据库

http://www.mybatis.org/mybatis-3/zh/index.html
<a href="http://www.mybatis.org/mybatis-3/zh/index.html">mybatis中文参考网站(一些属性定义方式,类型关系,类型映射等)<a>

2、MyBatis知识点

1.mybatis->dao层缓存

2.mybatis->输入映射,输出映射mybatis

3.mybatis->动态输出app

4.mybatis->关系映射(1-1,1-N,N-N)框架

5.mybatis->延迟加载dom

6.mybatis->查询缓存(一级缓存,二级缓存)

7.mybatis->整合Spring

8.mybatis->逆向工程

3、Mybatis初探( 单表实体类增删改查 )

  1. 加入jar:mybatis-3.2.6.jar或者mybatis-3.2.7.jar和日志包(log4j,commons-logging)

  2. 建立数据库表和全局配置文件SqlMapConfig.xml

USE `shop`;

/*Table structure for table `users` */

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(500) DEFAULT NULL,
  `sex` varchar(500) DEFAULT NULL,
  `birth` date DEFAULT NULL,
  `address` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
#db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
<?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>
  <!--加载数据源-->
  <properties resource="db.properties"></properties>
  <!-- 和Spring整合以后environments再也不须要使用 -->
  <environments default="development">
  
    <environment id="development">
      <transactionManager type="JDBC"/><!-- 使用JDBC的事务 -->
      <dataSource type="POOLED"><!-- 链接池 -->
        <property name="driver" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
      </dataSource>
    </environment>
    
  </environments>
  <!-- 加载映射文件 -->
  <mappers>
    <mapper resource="sqlmap/Users.xml"/>
    <mapper resource="mapper/UsersMapper.xml"/>
  </mappers>
</configuration>

3.编写实体JavaBean类和Mapper.xml对应文件

package com.ts.domain;

import java.util.Date;

public class Users {
	
	public Users() {}

	public Users(String name, String sex, Date birth, String address) {
		this.name = name;
		this.sex = sex;
		this.birth = birth;
		this.address = address;
	}

	private int id;
	
	private String name;
	
	private String sex;
	
	private Date birth;
	
	private String address;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Users [id=" + id + ", name=" + name + ", sex=" + sex + ", birth=" + birth + ", address=" + address
				+ "]";
	}
}
<?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">
    
<!-- namespace:命名空间 -->
<mapper namespace="Users">
	
	<!-- MappedStatement的ID -->
	<!--#{}:占位符 接收输入的参数
	
		parameterType:输入参数类型
		#{id}:参数名称是id
		
		resultType:输出结果类型
		返回一个JavaBean
	-->
	<select id="findUserById" parameterType="int" resultType="com.ts.domain.Users">
		select * from Users where id = #{id}
	</select>
	
	<!-- 
		${}:拼接符,拼接SQL字符串,${}中只能使用value,会有SQL注入问题,不建议使用
	 -->
	<select id="findUsersByName" parameterType="String" resultType="com.ts.domain.Users">
		select * from Users where name like '%${value}%'
	</select>
	
	<!-- 添加用户:返回自增主键值 ,只适用自增主键
		 keyProperty="id"返回映射Java属性
		 order="AFTER"执行顺序
		 resultType="int" 返回类型
		 
		 uuid:
		 <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
			select uuid
		</selectKey> 
	-->
	<insert id="insertUser" parameterType="com.ts.domain.Users">
		<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
			select LAST_INSERT_ID()
		</selectKey> 
		insert into Users(name,birth,sex,address) values(#{name},#{birth},#{sex},#{address})
	</insert>
	
	<!-- 删除用户 -->
	<delete id="deleteUser" parameterType="int">
		delete from Users where id = #{id}
	</delete>
	
	<!-- 更新用户 -->
	<update id="updateUser" parameterType="com.ts.domain.Users">
		update Users set name = #{name},sex = #{birth},birth = #{birth},address =#{address}  where id = #{id}
	</update>

</mapper>

4.测试增删改查代码

public class IMybatis {

	/**
	 * 需求:
	 * 根据ID查询单个用户
	 * 根据用户名称模糊查询用户
	 * 添加用户
	 * 删除用户
	 * 更新用户
	 * @throws Exception 
	 */
	private static SqlSessionFactory sqlSessionFactory;

	@Before
	public void before() throws IOException{
		//经过输入流读取全局配置信息建立工厂
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

	}
	
	/**
	 *  根据ID查询单个用户
	 * @throws Exception
	 */
	@Test
	public void findUserById() throws Exception{
		//获取SqlSession会话
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//查询一条记录,命名空间 + id
		Users user = sqlSession.selectOne("Users.findUserById",1);
		System.out.println(user);
		//释放资源链接
		sqlSession.close();
	}


	/**
	 * 根据用户名称模糊查询多条用户
	 * @throws Exception
	 */
	@Test
	public void findUsersByName() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		//查询多条记录
		List<Users> users = sqlSession.selectList("Users.findUsersByName","晓明");
		System.out.println( users.size() );
		sqlSession.close();
	}
	
	/**
	 * 添加用户
	 * @throws Exception
	 */
	@Test
	public void insertUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Users user = new Users("慧锦AAA", "女", new Date(), "北京");
		sqlSession.insert("Users.insertUser",user);
		sqlSession.commit();				
		//MySQL执行insert提交以前自动生成一个自增主键
		//经过MySQL函数能够获取刚插入记录的自增主键:LAST_INSERT_ID()
		System.out.println(user.getId());	//获取主键
		sqlSession.close();
	}
	
	
	/**
	 * 根据ID删除用户
	 * @throws Exception
	 */
	@Test
	public void deletetUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.delete("Users.deleteUser",6);
		sqlSession.commit();			
		sqlSession.close();
	}
	
	/**
	 * 更新用户
	 * @throws Exception
	 */
	@Test
	public void updateUser() throws Exception{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		Users user = new Users();
		user.setId(5);
		user.setName("名字");
		sqlSession.update("Users.updateUser", user);
		sqlSession.commit();
		sqlSession.close();
	}
相关文章
相关标签/搜索