【MyBatis框架】MyBatis入门程序第一部分

我们通过写一个简单的MyBatis小项目来在实战中学习MyBatis

1.需求
根据用户id(主键)查询用户信息
根据用户名称模糊查询用户信息
添加用户
删除 用户
更新用户

mybatis运行环境(jar包):
从https://github.com/mybatis/mybatis-3/releases下载,3.2.7版本

lib下:依赖包
mybatis-3.2.7.jar:核心 包

mybatis-3.2.7.pdf,操作指南

加入mysql的驱动包

加入的所有jar包如图(可以在这里下载:http://download.csdn.net/detail/u013517797/8781295)



2.创建log4j.properties
在src中放入日志配置文件

文件内容(拷贝自官方帮助文档)

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # Global logging configuration  
  2. #在开发环境下日志级别要设成DEBUG,生产环境设为INFO或ERROR  
  3. log4j.rootLogger=DEBUG, stdout  
  4. # MyBatis logging configuration...  
  5. log4j.logger.org.mybatis.example.BlogMapper=TRACE  
  6. # Console output...  
  7. log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
  8. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
  9. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n  
接下来创建SqlMapConfig.xml等文件

配置好之后的整个工程结构为图


3.SqlMapConfig.xml
SqlMapConfig.xml内容如下
(由于没有整合Spring,暂时在environments中配数据库连接池dataSource,整合Spring之后将这一块删除就行了)

<?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="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>

4.创建PO(persistant object持久对象)类
在数据库中创建mtbatis数据库,创建user表,表详细内容为
id<int>、username<vachar>、birthday<Date>、sex<int>、address<vachar>

在cn.edu.hpu.mybatis.PO包下创建PO对象
User.java:

package com.qianyan.mybatis.po;


import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 用户实体类
 * @author user
 *
 */
public class User implements Serializable{

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


public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address
+ "]";
}
}

5.编写User.xml配置文件
我们来写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="test">
<!-- 在mapper.xml文件中配置很多的sql语句,执行每个sql语句时,封装为MappedStatement对象
mapper.xml以statement为单位管理sql语句
 -->
 
  <!-- 根据id查询用户信息 -->
<!-- 
id:唯一标识 一个statement
#{}:表示 一个占位符,如果#{}中传入简单类型的参数,#{}中的名称随意
parameterType:输入 参数的类型,通过#{}接收parameterType输入 的参数
resultType:输出结果 类型,不管返回是多条还是单条,指定单条记录映射的pojo类型
-->
 <select id="findById" parameterType="int" resultType="com.qianyan.mybatis.po.User">
  select * from user where id = #{id}
 </select>
 
<!-- 根据用户名称查询用户信息,可能返回多条
${}:表示sql的拼接,通过${}接收参数,将参数的内容不加任何修饰拼接在sql中。
-->
 <select id="findByName" parameterType="java.lang.String" resultType="com.qianyan.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="com.qianyan.mybatis.po.User">
  <selectKey keyProperty="id" order="AFTER" resultType="int">
  select LAST_INSERT_ID()
  </selectKey>
  insert into user(username,sex,birthday,address) values(#{username},#{sex},#{birthday},#{address})
 </insert>
 <!-- mysql的uuid生成主键 -->
<!-- <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey keyProperty="id" order="BEFORE" resultType="string">
select uuid()
</selectKey>

INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})
</insert>
 -->
 <!-- oracle
在执行insert之前执行select 序列.nextval() from dual取出序列最大值,将值设置到user对象 的id属性
-->
<!-- <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey keyProperty="id" order="BEFORE" resultType="int">
select 序列.nextval() from dual
</selectKey>

INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})
</insert> -->

<!-- 删除 -->
  <delete id="deleteUser" parameterType="int">
  delete from user where id = #{id}
  </delete>
 
  <!-- 更新 -->
<update id="updateUser" parameterType="com.qianyan.mybatis.po.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}
</update>
</mapper>


6.在SqlMapConfig.xml中加载映射文件(User.xml)

<!-- 通过resource引用mapper的映射文件 -->
<mapper resource="sqlmap/User.xml" />

7.编写程序

(1)同归id查询用户
在cn.edu.hpu.mybatis.first包下编写测试样例MyBatisfirst.java
这里我们查询id为1的用户

package com.qianyan.mybatis.first;


import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;


import com.qianyan.mybatis.po.User;


/**
 * @author user
 */
public class MyBatisFirst {

//会话工厂
private SqlSessionFactory sqlSessionFactory;

// 创建工厂
@Before
public void init() throws IOException{

//配置文件(SqlMapConfig.xml)
String resource = "SqlMapConfig.xml";
// 加载配置文件到输入 流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}


// 测试根据id查询用户(得到单条记录)
@Test
public void testFindUserById(){
// 通过sqlSessionFactory创建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();

// 通过sqlSession操作数据库
// 第一个参数:statement的位置,等于namespace+statement的id
// 第二个参数:传入的参数
User user = null;
try {
user = sqlSession.selectOne("test.findById", 1);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭sqlSession
sqlSession.close();
}
System.out.println(user);
}

}

测试结果:张三
查看控制台Console输出的日志记录:

  1. DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.  
  2. DEBUG [main] - PooledDataSource forcefully closed/removed all connections.  
  3. DEBUG [main] - PooledDataSource forcefully closed/removed all connections.  
  4. DEBUG [main] - PooledDataSource forcefully closed/removed all connections.  
  5. DEBUG [main] - PooledDataSource forcefully closed/removed all connections.  
  6. DEBUG [main] - Opening JDBC Connection  
  7. DEBUG [main] - Created connection 29683960.  
  8. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.Connection@1c4f0f8]  
  9. DEBUG [main] - ==>  Preparing: SELECT * FROM USER WHERE id=?   
  10. DEBUG [main] - ==> Parameters: 1(Integer)  
  11. DEBUG [main] - <==      Total: 1  
  12. 张三  
  13. DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.Connection@1c4f0f8]  
  14. DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.Connection@1c4f0f8]  
  15. DEBUG [main] - Returned connection 29683960 to pool.

小结:
a.parameterType
在映射文件中通过parameterType指定输入参数的类型

b.resultType
在映射文件中通过resultType指定输出结果的类型

c.#{}和${}
#{}表示一个占位符号
${}表示一个拼接符号,会引起sql注入,所以不建议使用

d.selectOne和selectList
selectOne表示查询一条记录进行映射,使用selectList也可以使用,只不过只有一个对象
selectList表示查询出一个列表(参数记录)进行映射,不嗯能够使用selectOne查,不然会报下面的错:

org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值