MyBatis篇3-使用接口与xml映射器进行数据库操作

288 阅读8分钟

数据库操作

新增

<insert id="唯一值" parameterType="参数类的全名">
  insert into 表名(字段名...)  values (#{变量名}...);
</insert>

修改

<update id="唯一值" parameterType="参数类的全名">
  update 表名 set 字段名 = #{变量名} where 字段名 = #{变量名};
</update>

删除

<delete id="唯一值" parameterType="参数类的全名">
  delete from 表名 where 字段名 = #{变量名};
</delete>

查询(类属性与字段名不完全一致)

<resultMap type="表对应的实体类全类名" id="resultMap唯一值">
  <!-- id标签对应主键 -->
  <id property="类属性" column="字段"/>
  <result property="类属性" column="字段"/>
</resultMap>

<select id="唯一值" resultMap="resultMap的id">
  select * from 表名 where ...;
</select>

查询(类属性与字段名完全一致)

<!-- 使用resultType,必须类属性与字段名完全一致 -->
<select id="唯一值" resultType="表对应的实体类全类名">
  select * from 表名 where ...;
</select>

使用接口与xml映射器进行增删改

大致上分为五个文件:主配置文件、xml映射器、接口、实体类、调用程序

配置的更改集中在 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>
        <!-- 数据源环境配置 -->
    	<environments default="development">
    		<environment id="development">
    			<transactionManager type="JDBC" />
    			<dataSource type="POOLED">
    				<property name="driver" value="com.mysql.jdbc.Driver" />
    				<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;characterEncoding=UTF-8" />
    				<property name="username" value="root" />
    				<property name="password" value="root" />
    			</dataSource>
    		</environment>
    </environments>
	
		<!-- 主配置文件引入映射器 -->
	<mappers>
        <mapper resource="com/test/day38/StudentCURDMapper.xml" />
	</mappers>
</configuration>

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">

    <!-- 接口与xml映射器混合使用 -->
<mapper namespace="com.test.day38.StudentCURDInt">

    	<insert id="insertStu" parameterType="com.test.day38.Student">
		insert into student(id,name) values (#{id},#{name});
	</insert>

	<update id="updateStuById" parameterType="com.test.day38.Student">
		update student set name = #{name} ,age = #{age} where id = #{id};
	</update>
	
	<delete id="deleteStuById" parameterType="com.test.day38.Student">
		delete from student where id = #{id};
	</delete>
</mapper>

接口

package com.test.day38;

//接口和映射器混合使用:方法名与xml映射器中的id值对应
public interface StudentCURDInt {
 	//新增
	public int insertStu(Student stu);

        //根据id修改
	public int updateStuById(Student stu);
	
        //根据id删除
	public int deleteStuById(Student stu);
}

调用程序:接口和映射器混合使用

public class XmlAndInMapperTest {
    	public static void main(String[] args) {
    		Reader reader = null;
    		SqlSessionFactory sqlSessionFactory = null;
    		SqlSession session = null;
    		try{
    			//加载主配置文件,主配置文件中有数据库连接相关信息,还有映射器的相关信息
    			//参数是主配置文件的路径,我们的主配置文件是在跟路径下,所以直接写文件名就可以
			reader = Resources.getResourceAsReader("myBatis-config.xml");
			
			//创建SqlSessionFactory工厂
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
			//得到SqlSession对象,这个对象是操作映射器的对象
			session = sqlSessionFactory.openSession();
            
            //操作接口与xml混合映射器:getMapper(接口的class).调用的方法
            Student stu = new Student();
			stu.setId(41);
			stu.setName("新增学生");
			int res = session.getMapper(StudentCURDInt.class).insertStu(stu);//增
			
//			Student stu1 = new Student();
//			stu1.setId(41);
//			stu1.setName("修改学生");
//			stu1.setAge(22);
//			int res = session.getMapper(StudentCURDInt.class).updateStuById(stu1);//改
			
//			Student stu2 = new Student();
//			stu2.setId(41);
//			int res = session.getMapper(StudentCURDInt.class).deleteStuById(stu2);//删
			
			//提交session
			session.commit();
		}catch(Exception e){
			//如果发生异常回滚session
			session.rollback();
		}finally{
			//关闭资源
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			session.close();
		}
	}
}

测试用的实体类

package com.test.day38;

import java.io.Serializable;

public class Student implements Serializable{
    	private static final long serialVersionUID = 1L;
	
    	public Integer id;
	public String name;
	public Integer age;
	public String sex;
	public String classes;
	public Integer servlet;
	public Integer jsp;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getClasses() {
		return classes;
	}
	public void setClasses(String classes) {
		this.classes = classes;
	}
	public Integer getServlet() {
		return servlet;
	}
	public void setServlet(Integer servlet) {
		this.servlet = servlet;
	}
	public Integer getJsp() {
		return jsp;
	}
	public void setJsp(Integer jsp) {
		this.jsp = jsp;
	}
	
	@Override
	public String toString() {
		return "[id=" + id + ",name=" + name + ",age=" + age + ",sex=" + sex + ",classes="
				+ classes + ",servlet=" + servlet + ",jsp=" + jsp + "]";
	}
}

使用接口与xml映射器进行查询

大致上分为五个文件:主配置文件、xml映射器、接口、实体类、调用程序

配置的更改集中在 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>
        <!-- 数据源环境配置 -->
    	<environments default="development">
    		<environment id="development">
    			<transactionManager type="JDBC" />
    			<dataSource type="POOLED">
    				<property name="driver" value="com.mysql.jdbc.Driver" />
    				<property name="url" value="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;characterEncoding=UTF-8" />
    				<property name="username" value="root" />
    				<property name="password" value="root" />
    			</dataSource>
    		</environment>
    </environments>
	
		<!-- 主配置文件引入映射器 -->
	<mappers>
        <mapper resource="com/test/day38/StudentCURDMapper.xml" />
	</mappers>
</configuration>

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">

<!-- 接口与xml映射器混合使用 -->
<mapper namespace="com.test.day38.StudentCURDInt">
    	<!--当实体类的类属性与字段名不完全一致,比如本例实体类的属性classes对应数据库表中的字段class -->
            	<!--resultMap,用于java封装类与数据库表的属性对应 -->
        	<!--type是这个结果集映射的表对应的实体类的全路径
        		id,唯一的标识
        	 -->
        	<resultMap type="com.test.day38.Student" id="StudentMap">
        		<!-- id标签对应主键 -->
        		<id property="id" column="id"/>
        		<!-- 类的普通属性对应表的普通字段使用result标签 -->
        		<result property="name" column="name"/>
        		<result property="age" column="age"/>
        		<result property="sex" column="sex"/>
        		<result property="classes" column="class"/>
        		<result property="servlet" column="servlet"/>
        		<result property="jsp" column="jsp"/>
        	</resultMap>
     
         	<!-- 在select标签中,要不要使用parameterType参数,取决于查询需要不需要传递参数 -->
        	<select id="selectStuById" resultMap="StudentMap" parameterType="com.test.day38.Student">
        		select * from student where id = #{id};
        	</select>
         
         	<select id="selectStus" resultMap="StudentMap">
        		select * from student;
        	</select>
     
    <!--当实体类的类属性与字段名完全一致,就不需要使用resultMap创建属性对应表 -->
         	<!-- 可以使用resultType来接收结果集,必须类属性与字段名完全一致 -->
        	<select id="selUser" resultType="com.test.day38.User">
        		select * from user;
        	</select>
 </mapper>

接口

package com.test.day38;

//接口和映射器混合使用:方法名与xml映射器中的id值对应
public interface StudentCURDInt {

     //根据id查询
    public Student selectStuById(Student stu);
    
    //查询多条数据
    public List<Student> selectStus();
}

调用程序:接口和映射器混合使用

public class XmlAndInMapperTest {
    	public static void main(String[] args) {
    		Reader reader = null;
    		SqlSessionFactory sqlSessionFactory = null;
    		SqlSession session = null;
    		try{
    			//加载主配置文件,主配置文件中有数据库连接相关信息,还有映射器的相关信息
    			//参数是主配置文件的路径,我们的主配置文件是在跟路径下,所以直接写文件名就可以
			reader = Resources.getResourceAsReader("myBatis-config.xml");
			
			//创建SqlSessionFactory工厂
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			
			//得到SqlSession对象,这个对象是操作映射器的对象
			session = sqlSessionFactory.openSession();
            
                        //操作接口与xml混合映射器:getMapper(接口的class).调用的方法
			Student stu3 = new Student();
			stu3.setId(1);
			Student res = session.getMapper(StudentCURDInt.class).selectStuById(stu3);//单条查询:select * from student where id = #{id};
			System.out.println(res);
			
			List<Student> stus = session.getMapper(StudentCURDInt.class).selectStus();//多条查询:select * from student;
			System.out.println(stus);
			
			//提交session
			session.commit();
		}catch(Exception e){
			//如果发生异常回滚session
			session.rollback();
		}finally{
			//关闭资源
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			session.close();
		}
	}
}

测试用的实体类

package com.test.day38;

import java.io.Serializable;

public class Student implements Serializable{
    	private static final long serialVersionUID = 1L;
	
    	public Integer id;
	public String name;
	public Integer age;
	public String sex;
	public String classes;
	public Integer servlet;
	public Integer jsp;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getClasses() {
		return classes;
	}
	public void setClasses(String classes) {
		this.classes = classes;
	}
	public Integer getServlet() {
		return servlet;
	}
	public void setServlet(Integer servlet) {
		this.servlet = servlet;
	}
	public Integer getJsp() {
		return jsp;
	}
	public void setJsp(Integer jsp) {
		this.jsp = jsp;
	}
	
	@Override
	public String toString() {//打印的时候用,System.out.println(stus)等于System.out.println(stus.toString())
		return "[id=" + id + ",name=" + name + ",age=" + age + ",sex=" + sex + ",classes="
				+ classes + ",servlet=" + servlet + ",jsp=" + jsp + "]";
	}
}

关于使用接口与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">

<!-- 接口与xml映射器混合使用 -->
<mapper namespace="com.test.day38.StudentCURDInt">
    	<!--当实体类的类属性与字段名不完全一致,比如本例实体类的属性classes对应数据库表中的字段class -->
            	<!--resultMap,用于java封装类与数据库表的属性对应 -->
        	<!--type是这个结果集映射的表对应的实体类的全路径
        		id,唯一的标识
        	 -->
        	<resultMap type="com.test.day38.Student" id="StudentMap">
        		<!-- id标签对应主键 -->
        		<id property="id" column="id"/>
        		<!-- 类的普通属性对应表的普通字段使用result标签 -->
        		<result property="name" column="name"/>
        		<result property="age" column="age"/>
        		<result property="sex" column="sex"/>
        		<result property="classes" column="class"/>
        		<result property="servlet" column="servlet"/>
        		<result property="jsp" column="jsp"/>
        	</resultMap>
         
            <!-- 1 
        		当parameterType是八种数据类和String的时候
        		#{id}可以随意写,不用和接口的方法的参数名一致
        	 -->
        	<select id="selectStuById02" resultMap="StudentMap" parameterType="Integer">
        		select * from student where id = #{abc};
        	</select>
        	
        	<!-- 2
        		在做查询的时候,不是必需要使用实体类或实体类的resultMap
        		还可以直接使用map集合,写法resultType="Map"
        		在执行一次性查询结果,以后再也不用,可以使用map
        		如果要以后可能会在很多地方使用这个查询,结果经常被其他方法使用,这种的还是要写实体类的
        	 -->
        	<select id="selectStuById03" resultType="Map" parameterType="Integer">
        		select * from student where id = #{abc};
        	</select>
        	
        	
        	<!-- 3 
            	这个映射器对应的接口的方法,返回值是List<Map> 
             -->
        	<select id="selectStus02" resultType="Map">
        		select * from student;
        	</select>
        	
        	<!-- 4、多参数
            	public Map selectStu03(@Param("name")String name,@Param("cla")String classes);
            	这种参数传递方式,对增删改查都适用
        	 -->
        	<select id="selectStu03" resultType="Map" parameterType="String">
        		select * from student where name = #{name} and class = #{cla};
        	</select>
 </mapper>