一、需求

实现以下功能:
根据用户id查询一个用户信息
根据用户名称模糊查询用户信息列表
添加用户
更新用户
删除用户

二、具体步骤

1.增加pom引用

2.增加log4j.properties

# Global logging configuration
# 开发环境设置成debug,生产环境设置成info或者error
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
mybatis默认使用log4j作为输出日志信息。

3.SqlMapConfig.xml

在classpath下创建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>
<mappers>
<mapper resource="sqlmap/User.xml" />
</mappers>
</configuration>
SqlMapConfig.xml是mybatis核心配置文件,上边文件的配置内容为数据源、事务管理。

4、其他po类,mapper的编写参看全部代码

三、总结知识点

1.#{}和${}

#{}
  表示一个占位符号,#{}接收输入参数,类型可以是简单类型,pojo、hashmap。
  如果接收简单类型,#{}中可以写成value或其它名称。
  接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。
${}
  表示一个拼接符号,会引起sql注入,所以不建议使用${}。
  接收输入参数,类型可以是简单类型,pojo、hashmap。
  如果接收简单类型,${}中只能写成value。
  接收pojo对象值,通过OGNL读取对象中的属性值,通过属性.属性.属性...的方式获取对象属性值。

2.parameterType和resultType

parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。
resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。

3.selectOne和selectList

selectOne表示查询出一条记录进行映射。如果使用selectOne可以实现使用selectList也可以实现(list中只有一个对象)。
selectList表示查询出一个列表(多条记录)进行映射。如果使用selectList查询多条记录,不能使用selectOne。 
selectOne查询一条记录,如果使用selectOne查询多条记录则抛出异常:
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)

4.mapper中的namespace

  namespace :命名空间,用于隔离sql语句。
  注意:使用 mapper代理方式开发,namespace比较重要

5.sqlsession创建使用

// 配置文件
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 使用SqlSessionFactoryBuilder从xml配置文件中创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = null;
try {
  // 创建数据库会话实例sqlSession
sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById", 1);//执行sql
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}

6.mysql自增主键

<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<!-- selectKey将主键返回,需要再返回 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address)
values(#{username},#{birthday},#{sex},#{address});
</insert>
添加selectKey实现将主键返回
keyProperty:返回的主键存储在pojo中的哪个属性
order:selectKey的执行顺序,是相对与insert语句来说,由于mysql的自增原理执行完insert语句之后才将主键生成,所以这里selectKey的执行顺序为after
resultType:返回的主键是什么类型
LAST_INSERT_ID():是mysql的函数,返回auto_increment自增列新记录id值。
 
mysql可以使用以下:
    <!-- useGeneratedKeys="true"把新增加的主键赋值到自己定义的keyProperty(id)中 -->
 <insert id="insert" parameterType="com.bean.Person" useGeneratedKeys="true" keyProperty="id" >
insert into aa (id, item1)
values (#{id,jdbcType=BIGINT}, #{aa,jdbcType=INTEGER})
</insert>
useGeneratedKeys 取值范围true|false 默认值是:false。 含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。

7.Mysql使用 uuid实现主键

<insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">
  select uuid()
</selectKey>
  insert into user(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})
</insert>
注意这里使用的order是“BEFORE”
 使用mysql的uuid()函数生成主键,需要修改表中id字段类型为string,长度设置成35位。
 执行思路:
先通过uuid()查询到主键,将主键设置到user属性中,进而输入 到sql语句中。
 执行uuid()语句顺序相对于insert语句之前执行。

8.Oracle使用序列生成主键

首先自定义一个序列且用于生成主键,selectKey使用如下:
<insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User">
<selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">
  SELECT 自定义序列.NEXTVAL FROM DUAL
</selectKey>
  insert into user(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})
</insert>
注意这里使用的order是“BEFORE”
 
 
 
 

最新文章

  1. PHP对象Object的概念
  2. Linux- Nginx简单的负载均衡(一)
  3. C#集合类型
  4. 剑指offer系列57---整数中1出现的次数
  5. 解决java写入xml报错org.w3c.dom.DOMException:DOM002 Illeg
  6. react-native迁移版本遇到的问题
  7. mysql中多个字段共同确定唯一性
  8. python 实现单链表
  9. Mysql5.6.24 zip解压缩版配置及修改默认编码方法
  10. linux运维常用命令集
  11. [kuangbin带你飞]专题六 最小生成树 POJ 2421 Constructing Roads
  12. ntp-keygen.c
  13. PHP 单态设计模式复习
  14. Static语句块和初始语句块的使用---2015年10月恒生电子笔试试卷
  15. IT连创业系列:新的一年,先淫文一篇!
  16. linux dialog详解(图形化shell)
  17. iOS 如何查看APP的jetsamEvent日志
  18. SQL Server Profiler 常见问题总结
  19. GIS案例学习笔记-多边形内部缓冲区地理模型
  20. 详解UE4静态库与动态库的导入与使用

热门文章

  1. chrome浏览器开发者工具使用教程[转]
  2. Nginx伪静态配置和常用Rewrite伪静态规则集锦
  3. 制作ramdisk-u.img根文件系统
  4. 虚幻4 - ARPG实战教程(第一季)
  5. laravel 模版赋值
  6. weblogic11g重置控制密码
  7. Mybatis中的if test 标签
  8. 使用WdatePicker获取比当前时间大的写法
  9. Shell 将两个文件按列合并
  10. JS-点和中括号