Mybatis(一)

入门级程序

1.创建一个java工程mybatis-first
2.导入jar包
mybatis-3.2.7.jar
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar
javassist-3.17.1-GA.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
mysql-connector-java-5.1.7-bin.jar
3.创建一个SqlMapConfig.xml文件

SqlMapConfig.xml是mybatis核心配置文件,配置文件内容为数据源、事务管理。配置如下:

<?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>
	<!-- 和spring整合后 environments配置将废除 -->
	<environments default="development">
		<environment id="development">
			<!-- 使用jdbc事务管理 -->
			<transactionManager type="JDBC" />
			<!-- 数据库连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url"
					value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
</configuration>
4.创建pojo类

pojo类作为mybatis进行sql映射使用,po类通常与数据库表对应,

数据库user表如下:
在这里插入图片描述
User.java如下:

Public class User {
	private int id;
	private String username;// 用户姓名
	private String sex;// 性别
	private Date birthday;// 生日
	private String address;// 地址

get/set……
5.创建sql 映射文件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">
6.SqlMapperConfig.xml 中configuration标签中加载映射文件

三种方式加载mapper.xml 文件

  • 法一:
<mappers>
	<mapper resource="sqlmap/User.xml" /> 
</mappers>
  • 法二:
    此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中
    在这里插入图片描述
<mapper>
	<mapper class="com.itheima.mybatis.mapper.UserMapper" />
</mapper>
  • 法三:(企业中经常用这种)
    此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中(同上)
<mapper>
	<package name="com.itheima.mybatis.mapper"/>
</mappers>
7.在user.xml中添加标签,编写sql:
根据id 查询用户

标签中添加select标签,编写sql:

id:statement的id 或者叫做sql的id
parameterType:声明输入参数的类型
resultType:声明输出结果的类型,应该填写pojo的全路径 
#{}:输入参数的占位符,相当于jdbc的?
<mapper namespace="test">
	<select id="findUserById" parameterType="Integer"
		resultType="cn.itcast.mybatis.pojo.User">
		select * from user where id = #{随便写}
	</select>
</mapper>
根据用户名模糊查询用户
根据用户名模糊查询用户列表 ,
resultType 为list 的泛型
#{} 占位符
${} 字符串拼接,只能有value  '%${value}%'="%"#{}"%"
<select id="findUserByUsername" parameterType="String" resultType="com.itheima.mybatis.pojo.User">
	select * from user where username like '%${value}%'
</select>
添加用户

标签中添加insert标签,编写sql:

<insert id="insertUser" parameterType="com.itheima.mybatis.pojo.User" >
		<!-- 保存刚刚插入的id -->
		<selectKey keyProperty="id" resultType="Integer" order="AFTER">
			select LAST_INSERT_ID()
		</selectKey>
		insert into user(username,birthday,address,sex) values(#{username},#{birthday},#{address},#{sex})
</insert>
更新用户

标签中添加update标签,编写sql:

<update id="updateUser" parameterType="com.itheima.mybatis.pojo.User">
		update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}
</update>
删除用户

标签中添加delete标签,编写sql:

<delete id="deleteUserById" parameterType="Integer">
		delete from user where id=#{随便写}	
</delete>
8.编写测试类
public class MybatisFirstTest {

	@Test
	public void testMybatis() throws Exception {
		//加载核心配置文件
		String resource = "sqlMapConfig.xml";
		InputStream in = Resources.getResourceAsStream(resource);
		//创建SqlSessionFactory
		SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(in);
		//创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//通过id查询一个用户
		User selectOne = sqlSession.selectOne("test.findUserById", 1);
		System.out.println(selectOne);
		
		//根据用户名模糊查询用户列表
		List<User> selectUsers = sqlSession.selectList("test.findUserByUsername", "五");
		for(User user:selectUsers) {
			System.out.println(user);
		}
		
		//添加用户
		User user = new User();
		user.setId(8);
		user.setUsername("biubiu");
		user.setBirthday(new Date());
		user.setSex("女");
		user.setAddress("nj");
		sqlSession.insert("test.insertUser",user);
		sqlSession.commit();
		
		System.out.println(user.getId());
		
		//更新用户
		sqlSession.update("test.updateUser",user);
		sqlSession.commit();
		
		//删除用户
		sqlSession.delete("test.deleteUserById", 12);
		sqlSession.commit();
	}
}

Mybatis 动态代理开发

遵循四个原则:
 * 1.接口方法名 = User.xml 中id 的名
 * 2.返回值类型 = Mapper.xml 文件中返回值类型
 * 3.方法的入参类型 = Mapper.xml 中的入参类型
 * 4.命名空间的值 = 接口的全类名

UserMapper接口

public interface UserMapper {
	public User findUserById(Integer id);
}

UserMapper.xml

<mapper namespace=" com.itheima.mybatis.mapper.UserMapper">
	<!-- 通过id查询一个用户 -->
	<select id="findUserById" parameterType="Integer" resultType="User">
		select * from user where id = #{随便写}
	</select>
</mapper>

注意:
1.SqlMapConfig.xml 中可以通过typeAliases标签设置别名
  • 法一:
<typeAliases>
	<typeAlias type="com.itheima.mybatis.pojo.User" alias="User"/>
</typeAliases>
  • 法二:(一般用这种方法)
<typeAliases>
	<package name="com.itheima.mybatis.pojo"/>
</typeAliases>
2.SqlMapConfig.xml 中可以通过properties 标签导入配置文
<properties resource="db.properties"/>

db.properties配置文件内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

SqlMapConfig.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>
	<!-- 是用resource属性加载外部配置文件 -->
	<properties resource="db.properties"/>

	<!-- 和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>
<configuration>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值