MyBatis--------应用案例详解

1.首先看一下项目架构

2.建立一个student对象类

package com.cyn.po;

public class Student {
	private int Sno;
	private String Sname;
	private String Ssex;
	private int Sage;
	private String Sdept;
	public int getSno() {
		return Sno;
	}
	public void setSno(int sno) {
		Sno = sno;
	}
	public String getSname() {
		return Sname;
	}
	public void setSname(String sname) {
		Sname = sname;
	}
	public String getSsex() {
		return Ssex;
	}
	public void setSsex(String ssex) {
		Ssex = ssex;
	}
	public int getSage() {
		return Sage;
	}
	public void setSage(int sage) {
		Sage = sage;
	}
	public String getSdept() {
		return Sdept;
	}
	public void setSdept(String sdept) {
		Sdept = sdept;
	}
	

}

3.建立一个student实体类对应的数据库表t_student

4.建立student实体类映射器接口

package com.cyn.mapper;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.cyn.po.Student;
/*
 * 为了适应大多数情况,方法参数统一为POJO类型
 */
import com.sun.javafx.collections.MappingChange.Map;

public interface StudentMapper  {
	
	//增
	public int insertStudent(Student stu);
	//删
	public int deleteStudent(Student stu);
	//改
	public int updateStudent(Student stu);
	/*查
	 *切记:查询结果可能对应一个POJO,也可能为多个POJO对象集合!!
	 *多个返回值不在此处的讨论范围,灵活变通即可
	 */
	public Student selectStudent(Student stu);
	
	//通过Sname和Sdept进行多参数模糊查询(map)
	public Student selectStudentByMap(HashMap<String, String> parames);
	//通过Sname和Sdept进行多参数模糊查询(注解)
	public Student selectStudentByNote(@Param("Sname")String Sname,@Param("Sdept")String Sdept);
	//通过Sname和Sdept进行多参数模糊查询(POJO)
	public Student selectStudentByPojo(Student stu);
	/*通过map进行结果集存储(暂未实现略)
	public Map<String, Student> selectStudentSavedByMap(Student stu);*/
	//通过POJO进行结果集存储
	public List<Student> selectStudentSavedByPojo(Student stu);

}

5.映射器配置文件:StudentMapper.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.cyn.mapper.StudentMapper"><!-- 命名空间名在映射器代理中一定要与映射器接口类路径保持一致!-->
	 <!-- 1.1select通用格式一 -->
	 <!-- 一对多,对多个查询条件的异或查询只需一次select的编写 -->
	 <select id="selectStudent" parameterType="student" resultType="com.cyn.po.Student">
	 	select * from t_student
	 	<where>
	 		<if test="Sno != null and Sno != ''">
	 			and s_no = #{Sno}
	 		</if>
	 		<if test="Sname != null and Sname != ''">
	 			and s_name = #{Sname}
	 		</if>
	 		<if test="Sage != null and Sage != ''">
	 			and s_age = #{Sage}
	 		</if>
	 	</where> 
	 </select>
	 
	 <!-- 1.2select通用格式二 -->
	 <!-- 只允许单一条件选择查询,当条件均不满足时默认全部查询,以适应不同的需求灵活多变 -->
	 <!-- <select id="selectStudent" parameterType="student" resultType="com.cyn.po.Student">
    	select * from t_student
    	<where>
        	<choose>
	    		<when test="Sno != null and Sno != ''">
	        		and s_no = #{Sno}
	   		 	</when>
	    	 	<when test="Sname != null and Sname != ''">
					and s_name = #{Sname}
	    	 	</when>
	    		<otherwise>
					and s_age = #{Sage}
	    		</otherwise>
			</choose>
    	</where> 
	 </select>  -->
	
	<!-- 1.3select通用格式三 -->
	<!-- 在这里省略了foreach的使用,具体使用请查看动态SQL的总结 -->
	 
	<!-- 2.update通用格式 -->
	<!-- 一对多,当对单个字段或者多个字段的更新时只需一次update的编写 -->
	<!-- 一般情况下,对一张表而言,当更新条件一样,只需写出表的全部字段,即可满足对这张表所有的更新操作 -->
	 <update id="updateStudent" parameterType="student">
	 	update t_student 
	 	<set>
	 		<if test="Sname != null and Sname != ''">
	 			s_name = #{Sname},
	 		</if>
	 		<if test="Sage != null and Sage != ''">
	 			s_age = #{Sage},
	 		</if>
	 		<if test="Sdept != null and Sdept != ''">
	 			s_dept = #{Sdept},
	 		</if>
	 	</set>
	 	where s_no = #{Sno}
	 </update>
	 
	<!--  <update id="updateStudent" parameterType="student">
	 	update t_student 
	 	<set>
	 		<if test="Sname != null and Sname != ''">
	 			s_name = #{Sname},
	 		</if>
	 		<if test="Sage != null and Sage != ''">
	 			s_age = #{Sage},
	 		</if>
	 	</set>
	 	<where>
	 		<if test="Sno != null and Sno != ''">
	 			and s_no = #{Sno}
	 		</if>
	 		<if test="Sdept != null and Sdept != ''">
	 			and s_dept = #{Sdept}
	 		</if>
	 	</where>
	 </update> -->
	 
	 <!-- 3.insert通用格式 -->
	 <!-- 插入一条全字段或某些字段的记录信息,一张表对应一条insert的编写 -->
	 <insert id="insertStudent" parameterType="student">
	 	insert into t_student(s_no,s_name,s_age,s_dept) values(#{Sno},#{Sname},#{Sage},#{Sdept})
	 </insert>
	 
	 <!-- 4.delete通用格式 -->
	 <!-- 通过某一个或多个条件指定删除的记录信息 -->
	 <!-- 一般情况下,对一张表而言,可能有不同的删除条件,只需写出表的全部字段,即可满足对这张表所有不同条件的删除操作 -->
	 <delete id="deleteStudent" parameterType="student">
	 	delete from t_student 
	 	<where>
	 		<if test="Sno != null and Sno!= ''">
	 			and s_no = #{Sno}
	 		</if>
	 		<if test="Sname != null and Sname != ''">
	 			and s_name = #{Sname}
	 		</if>
	 		<if test="Sage != null and Sage != ''">
	 			and s_age = #{Sage}
	 		</if>
	 		<if test="Sdept != null and Sdept != ''">
	 			and s_dept = #{Sdept}
	 		</if>
	 	</where>
	 </delete>

	 
<!-- 。。。。。。。。。。。。。。。。。。。。。。。。。。。我是可爱的分割线。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 -->

	<!-- 
	1.多个参数的传递之Map的使用(将多个参数保存在集合域中)
	例如:
	-->
	 <select id="selectStudentByMap" parameterType="map" resultType="student">
	 	select * from t_student where s_name like concat('%',#{Sname},'%')
	 	and s_dept like concat('%',#{Sdept},'%')
	 </select>
	 
	<!-- 
	2.多个参数的传递之注解方式的使用(将多个参数保存在注解域中)
	例如:
	-->
	<select id="selectStudentByNote" resultType="student">
	 	select * from t_student where s_name like concat('%',#{Sname},'%')
	 	and s_dept like concat('%',#{Sdept},'%')
	</select>
	
	<!--  
	3.多个参数的传递之JavaBean的使用(将多个参数与JavaBean关联)
	 例如:
	-->
	<select id="selectStudentByPojo" parameterType="student" resultType="student">
	 	select * from t_student where s_name like concat('%',#{Sname},'%')
	 	and s_dept like concat('%',#{Sdept},'%')
	</select>
	
	<!-- 
	1.存储结果集之Map的使用(不推荐)
        暂未实现!!!
	切记:返回结果类型标签是resultType
	例如: 
	-->
	<select id="selectStudentSavedByMap" parameterType="student" resultType="map">
	 	select * from t_student where s_name like concat('%',#{Sname},'%')
	 	and s_dept like concat('%',#{Sdept},'%')
	</select>
	
	<!-- 
	2.存储结果集之POJO的使用(推荐)
	切记:返回结果集类型标签可以是resultMap-自定义POJO映射下才使用
	例如: 
	-->
	<select id="selectStudentSavedByPojo" parameterType="student" resultType="student">
	 	select * from t_student where s_name like concat('%',#{Sname},'%')
	 	and s_dept like concat('%',#{Sdept},'%')
	</select>

</mapper>



6.数据库配置文件:jdbc.properties

driver = com.mysql.jdbc.Driver
url= jdbc:mysql://localhost:3306/mybatis
username = root
password = 123456

7.日志配置文件:log4j.properties

log4j.rootLogger=DEBUG , stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

8.mybatis配置文件:mybatis-config.xml

<?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="jdbc.properties"><!-- 1.属性:引入properties配置文件 -->
		<!-- <property name="driver" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
		<property name="username" value="root"/>
		<property name="password" value="123456"/> -->
	</properties>
	
	<settings><!-- 2.设置  -->
		<setting name="useGeneratedKeys" value="false"/><!-- 是否允许JDBC自动生成主键 -->
		<setting name="autoMappingBehavior" value="PARTIAL"/><!-- 指定MyBatis的自动映射类型 -->
		<setting name="mapUnderscoreToCamelCase" value="true"/><!-- 是否开启自动驼峰命名规则,即从经典数据库列名字A_COLUMN到java对象属性名aColumn的映射 -->
		<!-- 注意:只有当设置为true且满足驼峰命名规则时,才可以实现从数据库到POJO对象的自动映射! -->
		<!-- 还有其他设置就不一一列举了,等用到了再回来添加 -->
	</settings>
	
	<typeAliases><!-- 3.类型别名 -->
		<!-- 设置student代替com.cyn.po.Student类,上下文均可使用,注意别名不区分大小写! -->
		<typeAlias alias="student" type="com.cyn.po.Student" />
	</typeAliases>
		<!-- 在java传递到数据库的参数和从数据库读出的数据中间起类型转换作用 -->
	<typeHandlers><!-- 4.类型处理器  -->
		
	</typeHandlers>
	
	<!-- <objectFactory type="">5.对象工厂 
	</objectFactory>-->
	
	<!-- <plugins/>6.插件  -->
	
	<environments default="development"><!-- 7.配置环境 -->
		<environment id="development"><!-- 8.环境变量 -->
			<transactionManager type="JDBC"><!-- 9.事务管理 -->
				<property name="autoCommit" value="false"/><!-- 设置为手动提交 -->
			</transactionManager>
			<dataSource type="POOLED"><!-- 10.数据源 -->
				<!-- 第一种:自定义配置数据库连接信息 -->
				<!-- <property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/> -->
				
				<!-- 第二种:引入properties文件配置数据库连接信息或者上下文引用定义,推荐这种方法 -->
				<property name="driver" value="${driver}"/>
				<property name="url" value="${url}"/>
				<property name="username" value="${username}"/>
				<property name="password" value="${password}"/>
			</dataSource>
		</environment>
	</environments>
	
	<!-- <databaseIdProvider type="">11.数据库厂商标识 
		MyBatis可能会运行在不同厂商的数据库中,它的作用在于指定SQL
		到对应的数据库厂商提供的数据库中运行! 
	</databaseIdProvider> -->
	
	<mappers><!-- 12.映射器 -->
		<!-- 第一种方法:用文件路径引入映射器,默认采取这一种方法 -->
		<mapper resource="com/cyn/mapper/StudentMapper.xml"/>
		
		<!-- 第二种方法:用包名引入映射器 -->
		<!-- <package name="com.cyn.mapper"/> -->
		
		<!-- 第三种方法:用类注册映入映射器 -->
		<!-- <mapper class="com.cyn.mapper.StudentMapper"/> -->
	</mappers>
	
</configuration>

9.mybatis工具类:SqlSessionFactoryUtil

package com.cyn.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/*
 *MyBatis工具类
 */
public class SqlSessionFactoryUtil {
	
	private static SqlSessionFactory sqlSessionFactory= null;
	private static final  Class CLASS_LOCK = SqlSessionFactoryUtil.class;
	private SqlSessionFactoryUtil(){}
	/*
	 * 构建SqlSessionFactory,用于读取mybatis配置信息
	 */
	public static SqlSessionFactory initSqlSessionFactory(){
		//1.设置mybatis配置文件
		String resource = "mybatis-config.xml";
		InputStream inputStream = null;
		try {
			//2.得到配置文件流
			inputStream = Resources.getResourceAsStream(resource);
			
		} catch (IOException ex) {
			System.out.println("获取inputStream异常");
			Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(Level.SEVERE,null,ex); 
			
			// TODO: handle exception
		}
		synchronized (CLASS_LOCK) {
			if(sqlSessionFactory == null){
				/*3.创建会话工厂,传入mybatis的配置文件信息
				 *读取配置信息,初始化mybatis
				 *连接数据库
				 *加载所有的映射器配置文件
				 *因为路径等错误导致加载失败,则可能会影响后面对数据库的操作 
				 */
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			}
		}
		return sqlSessionFactory;
	}
	
	/*
	 * 4.打开SqlSession,返回会话对象用于操作数据库
	 */
	public static SqlSession openSqlSession(){
		if(sqlSessionFactory == null){
			initSqlSessionFactory();	
		}
		return sqlSessionFactory.openSession();
	}
}

10.测试函数

package com.cyn.main;

import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.cyn.util.SqlSessionFactoryUtil;
import com.cyn.mapper.StudentMapper;
import com.cyn.po.Student;;

/*
 * 测试主函数
 */
public class Main {
	public static void main(String[] args) {
		SqlSession sqlSession = null;
		try {
			sqlSession = SqlSessionFactoryUtil.openSqlSession();
			
			/*第一种方法
			 *调用MyBatis原始代码接口对数据库进行增删改查
			 *例如:删除
			 */ 
			//int num=sqlSession.delete("com.cyn.mapper.StudentMapper.deleteStudent",student);
			
			
			/*第二种方法
			 *使用Mapper代理对象进行数据库的增删改查 
			 *例如:增删改查
			 */
			//创建StudentMapper对象,调用该方法mybatis自动生成mapper代理对象
			StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);
	
			/*实例化一个POJO对象
			 *注意一个POJO对象对应一张数据库表
			 *设置该对象的相关属性用于增删该查的条件(属性值实际应由前端界面传递)
			 *对象属性可以单一设置,也可以全部设置
			 *动态SQL会自动过滤POJO对象中的null字段,灵活多变
			 */
			Student student = new Student();
			student.setSno(95006);
			student.setSname("zhangsan");
			student.setSage(19);
			student.setSdept("linux");
			
		
			//1.通过Sno或Sname或Sage进行查询(多个参数的传递----POJO)
			//Student stu = stuMapper.selectStudent(student);	
			
			/*2.通过Sno进行更新
			int num = stuMapper.updateStudent(student);*/
			
			//3.插入新的学生信息
			int num = stuMapper.insertStudent(student);
			
			/*4.删除某条学生信息
			int num = stuMapper.deleteStudent(student);*/
			
			/*5.多个参数的传递----Map
			HashMap<String, String> paramsMap = new HashMap<String, String>();
			paramsMap.put("Sname", "li");
			paramsMap.put("Sdept", "li");
			Student stu = stuMapper.selectStudentByMap(paramsMap);*/
			
			/*6.多个参数的传递----注解
			String Sname = "li";
			String Sdept = "+";
			Student stu = stuMapper.selectStudentByNote(Sname,Sdept);*/
			
			/*7.多个参数的传递----POJO
			 * 经常使用
			 * 略
			*/
			
			/*8.存储结果集之Map的使用(不推荐)
			暂时未实现
			略*/
			
			/*9.存储结果集之POJO的使用(推荐)
			List<Student> stuList = stuMapper.selectStudentSavedByPojo(student);
			for(Student stu : stuList){
				System.out.println("该学生的姓名为:"+stu.getSname());
				
			}*/
			
			//测试语句
			//System.out.println("该学生的姓名为:"+stu.getSname());
			System.out.println("num:"+num);
			sqlSession.commit();
			
				
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			sqlSession.rollback();
			System.out.println("发生异常");
			//sqlSession.rollback();
			// TODO: handle exception
		}finally {
			if(sqlSession != null){
				sqlSession.close();	
			}
		}
	}
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值