【Mybatis】实例

   通过一个小例子,了解如何使用Mybatis。

   【需求】

   1、根据用户id查询一个用户信息(单条记录)

   2、根据用户名称模糊查询用户信息列表(多条记录)

   【过程】

   1、创建java工程

   2、加入mybatis核心包(从mybatis管网下载)、依赖包、数据驱动包

   

  3、编写 log4j.properties(mybatis默认使用log4j作为输出日志信息)和db..properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
   4、编写SqlMapConfig.xml

<configuration>

	<!-- 属性定义 加载一个properties文件 在 properties标签 中配置属性值 -->
	<properties resource="db.properties">
		<!-- <property name="" value=""/> -->
	</properties>

	<!-- 全局配置参数 -->
	<settings>
		<!-- 延迟加载总开关 -->
		<setting name="lazyLoadingEnabled" value="true" />	
		<!-- 设置按需加载 -->
		<setting name="aggressiveLazyLoading" value="false" />
		<!-- 开启二级缓存 -->
		<setting name="cacheEnabled" value="true"/>
	</settings>


	<!-- 和spring整合后 environments配置将废除 -->
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事务管理 -->
			<transactionManager type="JDBC" />
			<!-- 数据库连接池 -->
			<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>

	<!--加载mapper映射 如果将和spring整合后,可以使用整合包中提供的mapper扫描器,此处的mappers不用配置了。 -->
	<mappers>
		<!-- 通过resource引用mapper的映射文件 -->
		<mapper resource="sqlmap/User.xml" />

	</mappers>


</configuration>
   5、pojo(User.java)

        private int id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址
   6、User.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">
<!-- namespace命名空间,为了对sql语句进行隔离,方便管理 ,mapper开发dao方式,使用namespace有特殊作用
mapper代理开发时将namespace指定为mapper接口的全限定名
 -->
<mapper namespace="test">
<!-- 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象
mapper.xml以statement为单位管理sql语句
 -->

	<!-- 根据id查询用户信息 -->
	<!-- 
		id:唯一标识 一个statement
		#{}:表示 一个占位符,如果#{}中传入简单类型的参数,#{}中的名称随意
		parameterType:输入 参数的类型,通过#{}接收parameterType输入 的参数
		resultType:输出结果 类型,不管返回是多条还是单条,指定单条记录映射的pojo类型
	 -->
	<select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
		SELECT * FROM USER WHERE id= #{id}
	
	</select>
	
	<!-- 根据用户名称查询用户信息,可能返回多条
	${}:表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。
	
	 -->
	<select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">
		select * from user where username like '%${value}%'
	</select>
	
	<!-- 添加用户
	parameterType:输入 参数的类型,User对象 包括 username,birthday,sex,address
	#{}接收pojo数据,可以使用OGNL解析出pojo的属性值
	#{username}表示从parameterType中获取pojo的属性值
	selectKey:用于进行主键返回,定义了获取主键值的sql
	order:设置selectKey中sql执行的顺序,相对于insert语句来说
	keyProperty:将主键值设置到哪个属性
	resultType:select LAST_INSERT_ID()的结果 类型
	 -->
	<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
		<selectKey keyProperty="id" order="AFTER" resultType="int">
			select LAST_INSERT_ID()
		</selectKey>
		
		INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
	</insert>
	
	<!-- 用户删除  -->
	<delete id="deleteUser" parameterType="int">
	 delete from user where id=#{id}
	</delete>
	<!-- 用户更新 
	要求:传入的user对象中包括 id属性值
	-->
	<update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
		update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
	</update>

</mapper>

   7、测试程序

public class Mybatis_first {
	
	//会话工厂
	private SqlSessionFactory sqlSessionFactory;

	@Before
	public void createSqlSessionFactory() throws IOException {
		// 配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);

		// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);

	}

	// 根据 id查询用户信息
	@Test
	public void testFindUserById() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 通过sqlSession操作数据库
		   // 第一个参数:statement的位置,等于namespace+statement的id
		   // 第二个参数:传入的参数
			User user = sqlSession.selectOne("test.findUserById", 10);
			// 输出用户信息
			System.out.println(user);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}

	// 根据用户名称模糊查询用户信息
	@Test
	public void testFindUserByUsername() {
		// 数据库会话实例
		SqlSession sqlSession = null;
		try {
			// 创建数据库会话实例sqlSession
			sqlSession = sqlSessionFactory.openSession();
			// 查询单个记录,根据用户id查询用户信息
			List<User> list = sqlSession.selectList("test.findUserByUsername", "张");
			System.out.println(list.size());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}
}

   【比较】

   1、#{}和${}

   #{}:表示一个占位符,向占位符输入参数,mybatis自动进行java类型和jdbc类型的转换。程序员不需要考虑参数的类型,比如:传入字符串,mybatis最终拼接好的sql就是参数两边加单引号。通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

   ${}:表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。${}也可以接收pojo数据,可以使用OGNL解析出pojo的属性值。优缺点:使用${}不能防止sql注入,但是有时用${}会非常方便

   2、parameterType和resultType

   parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。

   resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。

      


   3、selectOne和selectList

   selectOne查询一条记录,如果使用selectOne查询多条记录则抛出异常:

   

   selectList可以查询一条或多条记录。

   【小结】

   1、编写SqlMapConfig.xml

    2、编写mapper.xml

          定义了statement

   3、编程通过配置文件创建SqlSessionFactory

   4、通过SqlSessionFactory获取SqlSession

   5、通过SqlSession操作数据库

          如果执行添加、更新、删除需要调用SqlSession.commit()

   6、SqlSesion使用完成要关闭

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值