使用MyBatis完成dao层简单的增删改查

使用MyBatis完成dao层简单的增删改查

	在使用mybatis时,普通的Java Project需要导入相应的mybatis的jar包和数据库连接的jar包,maven项目需要导入相应的依赖。

	mybatis的配置文件中,需要注意mapper文件的绝对路径是否正确,以及数据库连接配置信息是否正确,如下: 
<?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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<!-- mybatis数据库配置 -->
			<dataSource type="POOLED">
				<!-- 根据数据库版本使用不同的驱动,6.0版本以上使用com.mysql.cj.jdbc.Driver,6.0以下使用com.mysql.jdbc.Driver -->
				<property name="driver" value="com.mysql.cj.jdbc.Driver" />
				<!-- 数据库连接路径:其中可以除了必要的路径信息外,还可以在后面以?结尾添加UTF—8字符集设置(characterEncoding=UTF8)以及时区设置( serverTimezone=GMT)-->
				<property name="url" value="jdbc:mysql://localhost:3306/student?useUnicode=true&amp;characterEncoding=UTF8&amp;useSSL=false&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=GMT" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- 配置mapper映射文件的路径 -->
	<mappers>
		<!-- 需要执行的dao层的xml文件路径 -->
		<mapper resource="dao/StudentMapper.xml" />
	</mappers>
</configuration>

在确定mybatis配置文件没有问题后,开始写dao层的的mapper文件,在这个文件中需要注意各种标签的用法,相应的代码如下:
mapper文件的namespace中放入dao接口的路径一定要正确!
单表操作:

<?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">
<!-- namespce中放入dao接口的路径 -->
<mapper namespace="cn.kgc.tangcco.kgbd2010.dao.StudentDao">
	<!-- 修改方法 -->
	<update id="change1">
		update students set sage=#{age},sname=#{name} where
		sid=#{id}
	</update>
	<!-- 通过id查询信息 -->
	<select id="queryStuById"
		resultType="cn.kgc.tangcco.kgbd2010.model.Student">
		select * from students where sid=${id1}
	</select>
	<!-- 添加信息 -->
	<insert id="addStu1">
		insert into students
		values(#{students.sid},#{students.sage},#{students.sname})
	</insert>
	<!-- 查询所有信息 -->
	<select id="queryAllStu" resultMap="stu">
		select * from students
	</select>	
	<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="stu">
		<id property="sid" column="sid" />
		<!-- <result property="sname" column="sname"/> -->
		<result property="sage" column="sage" />
	</resultMap>
</mapper>

双表联合查询:

<!-- 双表联合查询 -->
	<select id="getStuWithScore" resultMap="ss">
		SELECT * from students s
		LEFT JOIN scores ss ON s.sid=ss.sid
	</select>
	<!-- id中放dao层的接口,resultMap中放数据库映射关系的id -->
	<select id="getStuWithObj" resultMap="so">
		select * from students s
		join objs o on s.sid=o.sid
	</select>

其中select中的resultMap根据对应的值调用resultMap模块:

<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="ss">
		<!-- id通过索引查询数据 -->
		<id property="sid" column="sid" />
		<!-- result通过遍历查询数据 -->
		<result property="sname" column="sname" />
		<result property="sage" column="sage" />
		<result property="xuefen" column="xuefen" />
		<!-- association中的property放实体类名称,javaType中放实体类的全限定名 -->
		<!-- association完成一对一查询,多列查询 -->
		<!-- 此处未使用association -->
		<collection property="score"
			ofType="cn.kgc.tangcco.kgbd2010.model.Score">
			<result property="bishi" column="bishi" />
			<result property="jishi" column="jishi" />
			<result property="zong" column="zong" />
		</collection>
	</resultMap>

	<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="so">
		<id property="sid" column="sid" />
		<result property="sname" column="sname" />
		<!-- collection中的property放实体类名称,javaType中放实体类全限定名 -->
		<!-- collection完成一对多查询,多行查询 -->
		<collection property="wupin"
			ofType="cn.kgc.tangcco.kgbd2010.model.Wupin">
			<result property="desc" column="desc" />
		</collection>
	</resultMap>

根据dao接口方法传入的参数(如对象数组,集合list,集合map)完成查询:

<!-- dao层传入对象数组 ,并根据对象数组查询相关信息 -->
	<!-- foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
     foreach元素的属性主要有 item,index,collection,open,separator,close。
           item :表示集合中每一个元素进行迭代时的别名
           index :指定一个名字,用于表示在迭代过程中,每次迭代到的位置
		   open :表示该语句以什么开始
           separator :表示在每次进行迭代之间以什么符号作为分隔符
           close :表示以什么结束
    -->
    <!-- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array -->
	<select id="getStuByAgeArray" resultMap="stu">
		select * from students where sage in
		<foreach collection="array" item="ages" open="(" close=")" separator=",">
			#{ages}
		</foreach>
	</select>
	<!-- 如果传入的是单参数且参数类型是一个list集合的时候,collection的属性值为list -->
	<select id="getStuByAgeArray2" resultMap="stu">
		select * from students where sage in
		<foreach collection="list" item="ages" open="(" close=")" separator=","> 
			#{ages}
		</foreach> 
	</select>
	<!-- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map -->
	<select id="getStuByMap" resultMap="stu">
		select * from students where xuefen &gt; #{xuefen} and sage in
		
		<foreach collection="ages" item="age" open="(" close=")" separator=",">
			#{age}
		</foreach>
	</select>

相应的resultMap调用模块:

<!-- resultMap中type放入实体类的全限定类名,id与上方sql语句调用的resultMap的名字一致 -->
	<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="stu">
		<id property="sid" column="sid" />
		<!-- <result property="sname" column="sname"/> -->
		<result property="sage" column="sage" />
	</resultMap>
	

使用where和if或者choose和when完成模糊查询或者多选一查询:

<!-- 使用where标签可以自动在sql语句中加上where条件关键字 -->
	<select id="getStuMH" resultMap="stu">
		select * from students
		<where>
			<if test="min!=null and max!=null">
				<!-- 可以使用between  and 完成区间查询-->
				and sage &gt; #{min} and sage &lt; #{max}
			</if>
			<if test="xuefen!=null and xuefen !=''">
				and xuefen &gt; #{xuefen}
			</if>
			<if test="name!=null">
				and sname like concat(#{name},'%')
			</if>
		</where>
	</select>
	<!-- choose标签 完成多选一条件筛选 -->
	<select id="getStuWhen"  resultMap="ss">
		select * from students s join scores ss on
		s.sid=ss.sid where 1=1
		<!-- <where> -->
			<choose>
				<when test="zong!=null">
					and zong &gt; #{zong}
				</when>
				<when test="xuefen!=null">
					and xuefen &gt; #{xuefen}
				</when>
				<otherwise>
					and sname like '张%'
				</otherwise>
			</choose>
		<!-- </where> -->
	</select>
其中需要调用的reslultMap模块和上面的模块一样:
<!-- resultMap中type放入实体类的全限定类名,id与上方sql语句调用的resultMap的名字一致 -->
	<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="stu">
		<id property="sid" column="sid" />
		<!-- <result property="sname" column="sname"/> -->
		<result property="sage" column="sage" />
	</resultMap>

	<resultMap type="cn.kgc.tangcco.kgbd2010.model.Student"
		id="ss">
		<!-- id通过索引查询数据 -->
		<id property="sid" column="sid" />
		<!-- result通过遍历查询数据 -->
		<result property="sname" column="sname" />
		<result property="sage" column="sage" />
		<result property="xuefen" column="xuefen" />
		<!-- association中的property放实体类名称,javaType中放实体类的全限定名 -->
		<!-- association完成一对一查询,多列查询 -->
		<!-- 此处未使用association -->
		<collection property="score"
			ofType="model.Score">
			<result property="bishi" column="bishi" />
			<result property="jishi" column="jishi" />
			<result property="zong" column="zong" />
		</collection>
	</resultMap>

以上在mapper文件中基本完成了dao层简单的增删改查。reslutMap的和reslutType的用法可以看下这个连接:reslutMap和resultType的用法

dao层接口:

public interface StudentDao {
//修改方法
int change1(@Param("id")int sid,@Param("age")int sage,@Param("name")String sname);
//通过id查询
Student queryStuById(@Param("id1")int sid);
//添加方法
int addStu1(@Param("students")Student stu);
//查询所有
List<Student> queryAllStu();
//双表查询,显示多列
List<Student> getStuWithScore();
//双表查询,显示多行
List<Student> getStuWithObj();
//传入对象数组
List<Student> getStuByAgeArray(Integer[] ages);
//传入list集合
List<Student> getStuByAgeArray2(List<Integer> ages);
//传入map集合
List<Student> getStuByMap(Map<String,Object> map);
//修改信息(使用trim标签)
int gaifen(@Param("xuefen")String xuefen,@Param("sname")String sname,@Param("sid")String sid);
//修改信息(使用set标签)
int gaifen1(@Param("xuefen")String xuefen,@Param("sid")String sid);
//查询信息(使用choose标签)
List<Student> getStuWhen(@Param("xuefen")String xuefen,@Param("zong")String zong);
//查询信息(使用where标签)
List<Student> getStuMH(@Param("min")String min,@Param("max")String max,@Param("name")String name,@Param("xuefen")String xuefen);
}

其中的@Param是注解,方便mapper文件引用传入的参数,#{}和 都 可 以 使 用 , 但 是 不 用 这 个 注 解 , 使 用 {}都可以使用,但是不用这个注解,使用 使使{}会报错,此时只能用#{}。

此时可以写一个测试类测试相应的接口功能:

public class Test {
	public static void main(String[] args) throws IOException {
	//获取SqlSeession
		String resource = "mybatis-config.xml";
		InputStream is = Resources.getResourceAsStream(resource);
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = factory.openSession(true);
 		//修改方法
//		int i = session.getMapper(StudentDao.class).change1(1,20,"啸天");
//		System.out.println(i);
		//通过id查询方法
//		Students s = session.getMapper(StudentDao.class).queryStuById(1);
//		System.out.println(s.getSname()+" "+s.getSage());
		//添加方法
//	    Student stu= new Student(2,18,"小天");
//		int i = session.getMapper(StudentDao.class).addStu(stu);
//		System.out.println(i);
   		//查询所有
//		List<Student> stus=session.getMapper(StudentDao.class).queryAllStu();
//		for(Student s:stus){
//			System.out.println(s.getSname()+" "+s.getSage());
//		}
		//双表联查,显示多列
//		List<Student> stus=session.getMapper(StudentDao.class).getStuWithScore();
//		for(Student s:stus){
//			
//			System.out.println(s.getSname()+" "+s.getSage());
//			for(Score sc:s.getScore()) {
//				System.out.println(sc.getBishi()+" "+sc.getJishi()+" "+sc.getZong()+"<--->");
//				
//			}
//			System.out.println();
//		}
		//双表联查,显示多行
//		List<Student> stus=session.getMapper(StudentDao.class).getStuWithObj();
//		for(Student s:stus){
//			System.out.println(s.getSname()+"带了");
//			for(Wupin w:s.getWupin()) {
//				System.out.println(w.getDesc());
//			}
//			System.out.println();
//		}
		//条件查询
//		List<Student> stus=session.getMapper(StudentDao.class).getStuMH(null,null,"韩","90");
//		for(Student s:stus){
//			
//			System.out.println(s.getSname()+" "+s.getSage());
//			System.out.println();
//		}
		//多选一条件查询
//		List<Student> stus = session.getMapper(StudentDao.class).getStuWhen("80", "90");
//		for (Student s : stus) {
//			System.out.println(s.getSname() + " " + s.getXuefen());
//			for (Score sc : s.getScore()) {
//				System.out.println(sc.getBishi() + " " + sc.getJishi() + " " + sc.getZong() + "<--->");
//			}
//			System.out.println();
//		}
    	//传入参数为对象数组
//		Integer[] ages= {21,22,23};
//		List<Student> stus=session.getMapper(StudentDao.class).getStuByAgeArray(ages);
//		for(Student s:stus){
//			
//			System.out.println(s.getSname()+" "+s.getSage());
//			System.out.println();
//		}
		//传入参数为map
		List<Integer> ages= new ArrayList<Integer>();
		ages.add(21);
		ages.add(22);
		ages.add(23);
		
        Map<String, Object> params=new HashMap<String, Object>();
		
		params.put("xuefen", 93);
		params.put("ages", ages);
		
		List<Student> stus=session.getMapper(StudentDao.class).getStuByMap(params);
		for(Student s:stus){
			
			System.out.println(s.getSname()+" "+s.getSage());
			System.out.println();
		}
	}
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值