[Spring+SpringMVC+Mybatis]框架学习笔记(八):Mybatis概述
第8章 Mybatis概述
8.1 几个概念
-
ORM
Object-Relationship Mapping 对象关系映射,它是一种思想,它的实质是将数据库中的数据用对象的形式表现出来。 -
JPA
Java Persistence API 它是JavaEE关于ORM思想的标准接口,仅仅是一套规范和接口,它不是实现。
Hibernate就是实现这一规范和接口的ORM组件(它是看不见SQL的)
MyBatis是一个半ORM组件(基于SQL开发)
8.2 什么是MyBatis
Mybatis是一个实现了Java数据持久化的开源框架,简单的来说,它就是一个jdbc的封装组件。
Mybatis的前身是ibatis,ibatis 创建于2002年,最初始apache下面的一个开源项目,2010迁移到google code,并更名为Mybatis。
当前最新版本是3.4.x;本次课程讲版本3.3.1
Mybatis的优势:
- 消除了大量的jdbc冗余代码(不用手动开关连接,创建statement,结果映射)
- 简单易学,容易上手(基于sql的编程思想,提供了简单易用的api与数据库进行交互)
- 很好的与各种数据库兼容(开发人员不需要考虑数据库间的差异性)
- 提供了第三方很好的支持(分页插件、逆向工程、缓存组件)
- 提供与Spring很好的集成支持。
8.3 Mybatis的开发环境搭建
1.新建Java项目,注意项目编码
2.引入mybatis的jar包:mybatis3.3.1.jar
3.引入mybatis依赖的jar包:
asm-3.3.jar (字节码生成器)
javassist-3.15.0.GA.jar (字节码生成器)
cglib-2.2.jar (cglib动态代理,字节码生成器)
commons-logging-1.1.1.jar (一个标准)
log4j-1.2.17.jar
4.引入Junit的包
junit-4.11.jar
hamcrest-core-1.3.jar
5.引入数据库的驱动包
mysql-connector-java-5.0.8-bin.jar
ojdbc14.jar
8.4 Mybatis的第一个Demo
8.4.1 测试数据准备
8.4.2 User实体类、Dao接口及实现类
1)User实体类
package com.steven.mybatis.sysmanage.entity;
import java.io.Serializable;
import java.sql.Timestamp;
public class User implements Serializable{
private static final long serialVersionUID = -7800274451115044222L;
private Long userId;
private String userName;
private String loginName;
private String password;
private Long deptId;
private Timestamp birthday;
private Timestamp tvUpdate;
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", loginName=" + loginName + ", password="
+ password + ", deptId=" + deptId + ", birthday=" + birthday + ", tvUpdate=" + tvUpdate + "]";
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
public Timestamp getTvUpdate() {
return tvUpdate;
}
public void setTvUpdate(Timestamp tvUpdate) {
this.tvUpdate = tvUpdate;
}
}
2)Dao接口
package com.steven.mybatis.sysmanage.dao;
import java.util.List;
import com.steven.mybatis.sysmanage.entity.User;
public interface IUserDao {
/**
* 根据用户id查询用户信息
* @param UserId
* @return
*/
public User getUserById(Long UserId);
/**
* 查询所有用户信息
* @return
*/
public List<User> getUserList();
/**
* 增加用户对象
* @param user
* @return
*/
public boolean addUser(User user);
/**
* 删除用户对象
* @param user
* @return
*/
public boolean delUser(User user);
/**
* 修改用户对象
* @param user
* @return
*/
public boolean updateUser(User user);
}
3)Dao接口实现类
package com.steven.mybatis.sysmanage.dao.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.steven.mybatis.sysmanage.dao.IUserDao;
import com.steven.mybatis.sysmanage.entity.User;
public class UserDao implements IUserDao{
private SqlSessionFactory sqlSessionFactory;
public UserDao(SqlSessionFactory sqlSessionFactory){
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User getUserById(Long UserId) {
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("user.getUserById", 1L);
sqlSession.close();
return user;
}
@Override
public List<User> getUserList() {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> userList = sqlSession.selectList("user.getUserList");
sqlSession.close();
return userList;
}
@Override
public boolean addUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.insert("user.addUser", user);
boolean flag = false;
if(rows > 0){
flag = true;
}
//注意:在做增删改操作时,要记得提交
sqlSession.commit();
sqlSession.close();
return flag;
}
@Override
public boolean delUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.delete("user.delUser", user.getUserId());
boolean flag = false;
if(rows > 0){
flag = true;
}
sqlSession.commit();
sqlSession.close();
return flag;
}
@Override
public boolean updateUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession();
int rows = sqlSession.delete("user.updateUser", user);
boolean flag = false;
if(rows > 0){
flag = true;
}
sqlSession.commit();
sqlSession.close();
return flag;
}
}
8.4.3 引入Mybatis的主配置文件
mybatis-config.xml
1)默认引用那个数据库环境
2)加入所有的sql对象映射文件
<?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>
<!-- 默认引用那个数据库环境 -->
<environments default = "defaultEnv">
<environment id="defaultEnv">
<!-- 事务管理方法 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 数据库连接四要素 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis_test"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!-- 加入所有的映射文件 -->
<mappers>
<mapper resource="userMapper.xml"></mapper>
</mappers>
</configuration>
8.4.4 引入对象映射文件
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 = "user">
<!--
1: id:表示一个sql句柄(相当于在jdbc的statement对象)
2: paremeterType :输入参数的类型 ,在sql语句中,通过占位符#{}来接收此参数
3: resultType: sql操作返回的结果类型
-->
<select id="getUserById" parameterType="java.lang.Long"
resultType="com.steven.mybatis.sysmanage.entity.User">
SELECT USER_ID USERID,USER_NAME USERNAME,LOGIN_NAME LOGINNAME,
BIRTHDAY,TV_UPDATE TVUPDATE FROM M_USER WHERE USER_ID = #{userId}
</select>
<!-- 查询所有用户的信息 -->
<select id="getUserList" resultType="com.steven.mybatis.sysmanage.entity.User">
SELECT USER_ID USERID,USER_NAME USERNAME,LOGIN_NAME LOGINNAME,
BIRTHDAY,TV_UPDATE TVUPDATE FROM M_USER
</select>
<!-- 增加用户 -->
<insert id="addUser" parameterType="com.steven.mybatis.sysmanage.entity.User">
INSERT INTO M_USER(USER_NAME,LOGIN_NAME,BIRTHDAY,TV_UPDATE)
VALUES(#{userName},#{loginName},#{birthday},#{tvUpdate})
</insert>
<!-- 删除用户 -->
<update id="delUser" parameterType="java.lang.Long">
DELETE FROM M_USER WHERE USER_ID = #{userId}
</update>
<!-- 修改用户 -->
<update id="updateUser" parameterType="com.steven.mybatis.sysmanage.entity.User">
UPDATE M_USER SET USER_NAME = #{userName},LOGIN_NAME=#{loginName},
BIRTHDAY=#{birthday} WHERE USER_ID = #{userId}
</update>
</mapper>
8.4.5 测试
1)读取Mybatis的主配置文件
2)通过sqlSessionFactoryBuilder创建一个sqlSessionFactory
3)通过sqlSessionFactory创建sqlSession
4)调用sqlSession接口的方法来执行数据库的操作
5)打印测试
6)关闭sqlSession
package com.steven.mybatis.sysmanage.test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import com.steven.mybatis.sysmanage.dao.IUserDao;
import com.steven.mybatis.sysmanage.dao.impl.UserDao;
import com.steven.mybatis.sysmanage.entity.User;
public class IbatisInterfaceTest {
static Logger log = Logger.getLogger(IbatisInterfaceTest.class);
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException{
//1.读取Mybatis的主配置文件
String configFile = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(configFile);
//2.创建SqlSessionFactory对象
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testGetUserById(){
IUserDao userDao = new UserDao(sqlSessionFactory);
log.info("根据用户id查询结果为:" + userDao.getUserById(1L));
}
@Test
public void testGetUserList(){
IUserDao userDao = new UserDao(sqlSessionFactory);
log.info("查询所有用户记录行数为:" + userDao.getUserList().size());
}
@Test
public void testAddUser(){
IUserDao userDao = new UserDao(sqlSessionFactory);
User user = new User();
user.setUserName("zhangsan");
user.setLoginName("Mike");
user.setBirthday(new Timestamp(88,3,25,0,0,0,0));
log.info("增加用户操作是否成功:" + userDao.addUser(user));
}
@Test
public void testUpdateUser(){
IUserDao userDao = new UserDao(sqlSessionFactory);
User user = new User();
user.setUserId(2l);
user.setUserName("zhangsan");
user.setLoginName("Jerry");
log.info("更改用户操作是否成功:" + userDao.updateUser(user));
}
@Test
public void testDelUser(){
IUserDao userDao = new UserDao(sqlSessionFactory);
User user = new User();
user.setUserId(2l);
log.info("删除用户操作是否成功:" + userDao.delUser(user));
}
}