MyBatis

#MyBatis

##JAVA实现
Mybatis访问数据库的方法是通过其中的SqlSession.****() 方法来实现.
要得到SqSession 需要通过SqlSessionFatory.openSession()来实现,
SqlSessionFatory又需要SqlSessionFatoryBuilder.build() 来实现,
new SqlSessionFatoryBuilder(SqlMapConfig.xml)其中需要SqlMapConfig.xml配置文件

##1.SqlMapConfig.xm配置

<?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> //源配置
<typeAliases>
   <package name="com.sp.pojo"/>    //<typeAliases></typeAliases>中配置的resulttype和paramtype 
</typeAliases>                     //的类型映射,例如com.sp.Student则可以直接写student
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" /> // ${}读取源配置
				<property name="url" value="${url}" />
				<property name="username" value="${user}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers >
	  <mapper resource="mappers/StudentMapper.xml"/>  //映射的map
	</mappers>
</configuration> 

##2.mapper.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="tt">
<select id="findAll" resultType="com.sp.pojo.Student">  //resultType 查询返回的对象类型
 select * from students   //SQL语句
</select>
<select id="insert" parameterType="com.sp.pojo.Student" > //parameterType 传递参数类型 
 INSERT INTO students value (null,#{sname},#{sex},#{age},#{cid},#{addr},#{birth})
</select>
<select id="delete" parameterType="_int">
    DELETE FROM students where sid=#{sid}   //单值 #{任意字符}  ${只能为value}
 </select>
<select id="findOne" parameterType="_int" resultType="student"> //这里可以写student
    SELECT * FROM students where sid=${value}
</select>
<select id="update" parameterType="com.sp.pojo.Student" >
   UPDATE students set sname=#{sname}, sex=#{sex},age=#{age},cid=#{cid},addr=#{addr},birth=#{birth} where sid=#{sid}
</select>
</mapper>

##3.工具类得到sqlSession

public class MyBatisUtil {

	private static SqlSessionFactory getSSFactory(String configName) {

		try {
			InputStream inputStream = Resources.getResourceAsStream(configName);
			return new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;

	}

	// true自动提交 flase为不自动提交(默认值)
	public static SqlSession getSqlSession(boolean isAutoCommit) {
		SqlSessionFactory sqlSessionFactory = getSSFactory("SqlMapConfig.xml");
		return sqlSessionFactory.openSession(isAutoCommit);

	}

	// 这里默认为不自动提交
	public static SqlSession getSqlSession() {
		SqlSessionFactory sqlSessionFactory = getSSFactory("SqlMapConfig.xml");
		return sqlSessionFactory.openSession();

	}

}

##4.测试单元

public class TestMyBatis {
  //查询所有学生
	@Test
	public void testAll() {
		  SqlSession sqlSession = MyBatisUtil.getSqlSession();
		  List<Student> students = sqlSession.selectList("tt.findAll");
		  for (Student student : students) {
			  System.out.println(student);
		}
	}
	   //查询单个学生
		@Test
		public void testFindOne() {
			  SqlSession sqlSession = MyBatisUtil.getSqlSession();
			  int sid = 26;
			  Student student = sqlSession.selectOne("tt.findOne", sid);
				  System.out.println(student);
		}
	   //添加学生
		@Test
		public void testInsert() {
			  SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
			  Date date = new Date(1535620136);
			  System.out.println(date);
			  Student student = new Student("小白", "男", "22", "1", "伤害",date, "三");
			  sqlSession.insert("tt.insert",student);
			  System.out.println("添加成功");
		}
		
		//刪除学生
				@Test
				public void testdelete() {
					  SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
					  int sid = 25;
					  sqlSession.delete("tt.delete", sid);
					  System.out.println("删除成功");
				}
		
				//修改学生
				@Test
				public void testUpdate() {
					  SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
					  Student student = sqlSession.selectOne("tt.findOne", 26);
					  student.setSname("小白白白白");
					  System.out.println(student);
					  sqlSession.update("tt.update",student);
					  System.out.println("修改成功");
				}
}

##{}和${}小结:
(1) #{}表示一个占位符号,通过#{}可以实现preparedStatement 向占位符中设置值,自动
进行java 类型和jdbc 类型转换。#{}可以有效防止sql 注入。#{}可以接收简单类型值或pojo
属性值。如果parameterType 传输单个简单类型值,#{}括号中可以是value 或其它名称。
(2) 表 示 拼 接 s q l 串 , 通 过 {}表示拼接sql 串,通过 sql{}可以将parameterType 传入的内容拼接在sql 中且不进行
jdbc 类型转换, 可 以 接 收 简 单 类 型 值 或 p o j o 属 性 值 , 如 果 p a r a m e t e r T y p e 传 输 单 个 简 单 类 型 值 , {}可以接收简单类型值或pojo 属性值,如果parameterType 传输单个简单 类型值, pojoparameterType{}括号中名称只能是value。

注意: **** _int 对应int基本 int 对应Integer ***

#注解实现

##1.SqlMapConfig.xml配置文件

<configuration>

<properties resource="db.properties"></properties>
**//这里是通过接口中的方法来得到paramType 以及 ResultType 所以不需要映射类型pojo包**
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${user}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers >
	  <package name="com.sp.mapper"/>
	</mappers>
</configuration> 

##2.mapper接口

package com.sp.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.sp.pojo.Classes;

public interface ClassesMapper {
    @Select("select * from classes")
	public List<Classes> findAll();
}


##3.工具类同上

##4.测试单元

	//测试注解方法查找班级list
	@Test
	public void testClassesFind(){
		SqlSession sqlSession = MyBatisUtil.getSqlSession();
		 ClassesMapper classesmapper = sqlSession.getMapper(ClassesMapper.class);
		 List<Classes> classes = classesmapper.findAll();
	 System.out.println(classes);
	}

##小结

对比上面两种可以看出,MyBatis可以通过代理来实现接口对象,使用接口中的方法来访问数据库,并且其中
的paramtype和ResultType都无需再通过xml定义. 注解方式比较贴近与spring框架整合的状态,
要把接口放入到spring容器中就需要通过MyBatis框架来实现接口的代理后纳入到spring容器中

#Mybatis与Spring整合

需要mybatis-spring-1.3.2.jar 包

在applicationContext.xml中配置即可

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    	<!-- 扫描包 -->
   	<context:component-scan base-package="com.sp"/>
   	   	<!-- 数据源配置文件导入 -->
	<context:property-placeholder location="classpath:db.properties"/>
	   	<!-- 配置DataSource,这里采用阿里巴巴的 -->
	 <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
	  <property name="driverClassName" value="${driver}"/>
	  <property name="url" value="${url}"/>
	  <property name="username" value="${user}"/>
	  <property name="password" value="${password}"/>
	 </bean>
	  	 <!-- 配置SqlSessionFatoryBean,以代理实现接口 -->
	  <bean name="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
	        <!-- 必要一个数据源,才能够访问数据库 -->
	   <property name="dataSource" ref="dataSource"/>
	       	<!-- 这个是映射的mapper,需要和接口对应,其中放sql语句 -->
	   <property name="mapperLocations" value="classparth:mapper/*.xml"/>
	        	<!-- 配置一个paramtype以及ResultType的依赖包,方便后续简写类型 --> 
	   <property name="typeAliasesPackage" value="com.sp.pojo"/>
	  </bean>
	        	<!-- 接口实现的配置工厂 -->
	   <bean name="MapperScannerConfigurer"  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	        	<!-- 找到需要实现的接口包 -->
	        <property name="basePackage" value="com.sp.mapper"/>
	        	<!-- 对应使用的代理工厂 -->
	        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
	    </bean>
</beans>


##关键点

name=“sqlSessionFactoryBean” class=“org.mybatis.spring.SqlSessionFactoryBean”
这个为接口代理工厂

   <bean name="MapperScannerConfigurer"  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        	<!-- 找到需要实现的接口包 -->
        <property name="basePackage" value="com.sp.mapper"/>
        	<!-- 对应使用的代理工厂 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
    </bean>

这里为链接实现接口代理工厂和接口的位置的桥梁

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值