Mybatis_2.基于XML的增删改查

1.实体类User.java

    public class User {
         private int id;
         private String name;
         private int age;
         //getter、setter...
    }

2.映射文件userMapper.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.test.withXml.UserMapper">
	<!-- 自定义结果集 -->
	<resultMap type="com.test.bean.User" id="userMap">
		<id property="id" column="id" javaType="java.lang.Integer"/>
		<result property="name" column="name" javaType="java.lang.String"/>
		<result property="age" column="age" javaType="java.lang.Integer"/>		
	</resultMap>
	<!-- 增删改查标签的id属性必须和接口中的方法名相同,
		id属性值必须是唯一的,不能够重复使用,
		parameterType属性表示形参参数类型,
		resultType属性表示查询时返回的结果集类型 
	-->
	<!-- userGeneratedKeys(仅对insert有用),会告诉Mybatis使用JDBC的getGeneratedKeys方法来取出由MySQL内部生成的主键,
		默认值false。
		keyProperty(仅对insert有用)标记一个属性,mybatis会通过getGeneratedKey或者通过insert语句的selectKey子元素设置值
		默认不设置。
	-->
	<insert id="addUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.test.bean.User">
		insert into users (name,age) values (#{name},#{age})
	</insert>
	
	<delete id="deleteUser" parameterType="int">
		delete from users  where id = #{id}
	</delete>
	
	<update id="updateUser" parameterType="com.test.bean.User">
		update users set name=#{name},age=#{age} where id=#{id} 
	</update>
	
	<select id="queryUser" parameterType="int" resultType="com.test.bean.User" >
		select * from users where id = #{id}
	</select>
	
	<select id="queryAllUser" resultMap="userMap">
		select * from users
	</select>
	
	<select id="queryBuyName" parameterType="String" resultMap="userMap">
		select * from users where name like #{name}
	</select>	
	
</mapper>

3.全局配置文件mybatis.cfg.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="mysql.properties"></properties>
	<!-- 配置mybatis运行环境,development:开发模式,work:工作模式-->
	<environments default="development">
		<environment id="development">
			<!-- type=“jdbc”表示使用JDBC的提交和回滚来管理事务 -->
			<transactionManager type="JDBC" />
			<!-- mybatis提供了三种数据源类型,POOLED,UNPOOLED,JNDI -->
			<!-- POOLED:表示支持JDBC数据源的连接池 -->
			<!-- UNPOOLED:表示不支持JDBC数据源的连接池 -->
			<!-- JNDI:表示支持外部数据源连接池 -->
			<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>
		<!-- 基于xml映射文件的增删改查,注册映射文件 -->
		<mapper resource="com/test/withXml/userMapper.xml"/>
	</mappers>
	<!-- 为实体类定义别名,简化sql映射xml文件中的引用 -->
	<!-- <typeAliases>
		<typeAlias type="com.test.bean.User" alias="_User"/>
	</typeAliases> -->
</configuration>

4.数据库配置文件mysql.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis1?useUincode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

5.测试类

/**
 * @author:滕鹏飞 
 * @version: 1.0
 * @Created on: 2018-9-2 下午8:32:54
 * 类说明:基于XML文件
 */
public class Test {

	public static void main(String[] args) {
		//addUser();
		//delete();
		//update();
		//query();
		queryBuyName();
	}
	
	/**
	 * 添加数据
	 */
	public static void addUser(){
		SqlSession sqlSession = DBUtil.getSession();
		User user = new User("张三三", 21);
		sqlSession.insert("com.test.withXml.UserMapper.addUser",user);
		sqlSession.close();
	}
	
	/**
	 * 删除数据
	 */
	public static void delete(){
		SqlSession sqlSession = DBUtil.getSession();
		sqlSession.delete("com.test.withXml.UserMapper.deleteUser","3");
		sqlSession.close();
	}
	
	/**
	 * 修改数据
	 */
	public static void update(){
		SqlSession sqlSession = DBUtil.getSession();
		User user = new User(5,"张三三", 21);
		sqlSession.update("com.test.withXml.UserMapper.updateUser", user);
		sqlSession.close();
	}
	
	/**
	 * 查找数据
	 */
	public static void query(){
		SqlSession sqlSession = DBUtil.getSession();
		User user = sqlSession.selectOne("com.test.withXml.UserMapper.queryUser", 4);
		System.out.println(user);
	}
	
	/**
	 * 根据name进行模糊查询
	 */
	public static void queryBuyName(){
		SqlSession sqlSession = DBUtil.getSession();
		List<User> user = sqlSession.selectList("com.test.withXml.UserMapper.queryBuyName", "%三%");
		System.out.println(user);
	}
}

注意:

1.若使用自定义结果集则使用结果集的属性为resultMap,不是resultType,若使用全类名则使用resultType
2.入参:
  parameterType:可以是类,需要写全类名,也可以是基本数据类型
  出参:
  自定义类型:resultMap
  指定类型:resultType
3.自动提交事务:
    1.sessionFactory.openSession(true);     
    2.session.commit();该方式增删改都必须添加,查询可以不用
4.若同时使用XML文件映射SQL和映射文件对应的接口,比如UserMapper.java和userMapper.xml,若在映射文件中使用namespace属性,则在配置文件中就不需要在引入,否则需要同时引入接口类和映射文件,namespace命名规范:映射文件所在路径+映射文件名。
5.表字段的名称和类属性的名称不一致的情况
解决办法一: 通过在查询的sql语句中定义字段名的别名,让字段名的别名和实体类的属性名一致,这样就可以表的字段名和实体类的属性名一一对应上了,这种方式是通过在sql语句中定义别名来解决字段名和属性名的映射关系的。
select t_id id, t_name name from teacher where t_id = #{id}     
解决办法二: 通过<resultMap>来映射字段名和实体类属性名的一一对应关系。这种方式是使用MyBatis提供的解决方式来解决字段名和属性名的映射关系的。
<resultMap type="com.test.bean.User" id="userMap">
    <id property="id" column="id" javaType="java.lang.Integer"/>
    <result property="name" column="name" javaType="java.lang.String"/>
    <result property="age" column="age" javaType="java.lang.Integer"/>       
</resultMap>
原文地址:https://www.cnblogs.com/tengpengfei/p/10453930.html